Jump to content

ChenXiu

Members
  • Posts

    177
  • Joined

  • Last visited

Everything posted by ChenXiu

  1. Circumstance: "label.php" is actually PHP "readfile" page that fetches images from a private root directory. "customer.html" is the public page where visitors view their images like this: Dear Customer, Here Is Your Image: <img src="label.php?image=id_number_1001.png"> Question: Is it okay to use a hidden $_SESSION["filename"] and change what I have now: Dear Customer, Here Is Your Image: <img src="label.php?image=id_number_1001.png"> To this: Dear Customer, Here Is Your Image: <img src="label.php"> This works by having the actual image name stored in a hidden session variable, using the following lines of code on my readfile page "label.php" like this: $imgName = $_SESSION[ "filename" ] . ".png"; $imgPath = "../root_directory/" . $imgName; Since I do not want customers to be allowed to ever see the image again after logging out, is it okay to rely on a hidden session variable for the filename as I described above? (Potential hackers will be less tempted to "try different image names and numbers" like "id1.png, id2.png, id3.png" because they will have no idea if the image will be a gif, jpeg, or png, nor have any idea of a numbering sequence.) Thank you!!
  2. LOL -- the "&" and the "|" are right next to each other on my keyboard 😃 Actually, there comes a point at the end of the day where no matter what I type it is wrong and it generates an error. echo hello; (oops I forgot the quotes). echo 'hello' (oops I forgot the semicolon). But thank you for pointing that out, I'll double-check my actual code to make sure it's not really that way. Thank you, those are very good points. To paraphrase back to you what you said to ensure I understand the idea, it sounds like the proper way to do this is to, no matter what, have the $_SESSION["username"] always set with minimum default values.... then add/change permissions via mySQL as necessary -- thus: 1.) making the check for isset($_SESSION["username"]) unnecessary 2.) giving better (more uniform) control over users (via backend, without needing the user to logout then log back in) 3.) Future-proofing (although just 2 users today, maybe 50 users a year from now). A year ago, I would have said "doing it that way is complicated and a big waste of time because there's only myself and one other user." But I've quickly learned that if I don't code stuff correctly in the beginning, I end up spending days and days re-coding everything per the advice given right here that I should have followed in the beginning 😁
  3. Interesting! Both your ideas - the "placeholder image" with the words "no image here" sounds perfect, and, the storing the real filenames in a database sound excellent. I'm thinking because you made these suggestions, you must be saying there's no way for PHP code (on my html page) to verify what my readfile.php page is generating, right? For example, my html page says: Dear Customer, here is your image: <img src="label.php?label=<?= $filename ?>.jpg"> So there's no such line of PHP code I could precede that with? For example, something that like this pseudocode: <?php if( ! image ("label.php?label=<?= $filename ?>.jpg")) echo "no image"; ?> I'm assuming this cannot be done -- I tried lots of stuff that didn't work.
  4. 😃 Okay I got another one: if(!isset($_SESSION["username"]) && $_SESSION["username"] != 'admin')) { exit; } That's another one I wish I could shorten. If I just do "if($_SESSION["username"] != 'admin')" then I'll get an "undefined index 'username'" error if $_SESSION["username"] wasn't already set...
  5. An image is saved in the root directory. The page "label.php" uses "readfile" to access and display the image using code like this: $file = '../image.jpg'; // IN ROOT DIRECTORY $type = 'image/jpeg'; header('Content-Type:'.$type); header('Content-Length: ' . filesize($file)); readfile($file); The image then gets embedded into an html page and displayed like this: Dear Customer, here is your image: <img src="label.php?label=<?= $filename ?>.jpg"> QUESTION: in the event of an error, how do I dipslay the readfile error on the customer's html page? Even though I have error trapping in the "readfile" code in "label.php" file -- like if a parameter is missing, I'll have exit( "NO IMAGE GENERATED" ). But this error message won't display on the customer's html page because html treats <?= $filename ?>.jpg" like it's a real image instead of displaying the readfile's "NO IMAGE GENERATED" exit error. Make sense? No. I probably have to rewrite my question 😃
  6. Is there a shorthand for: if( $dog != 'bark' ) exit( ' go away ' ); This obviously doesn't work (but I tried it anyway 😃 ) ( $dog != 'bark' ) ?? exit( ' go away ' ); .... I also tried every permutation of: $dog = 'bark' ?? exit('go away'); Maybe a stupid question... after typing it out, if($dog!='bark') exit('go away'); looks pretty short already.
  7. That is fantastic! I also like your change to line 6 -- it makes for clearer code. These days I'm learning to make my code neater, and to use actual words (like your $sku['products']) so at a later time, I know what the heck my code means. Years ago I thought it "saved space" and "made PHP faster" if I scrunched everything on one line! (made-up example): $aaa=array($cz =>$w8);$c=$5;foreach($a as $b){if($b!=0){$czn = $rrr}} <--- OMG! That works fine until 6 months later an "error on line 10" appears and not only do I not remember what any of the variables mean, I can't find the line -- because the entire code is all on one line haha LOL. Anyway, thank you!!
  8. I know, I agree! But I can't. That posted array comes from a 3rd party. Actually, not too long ago when you were helping me with another mySQL issue, I learned about how use create those mini-arrays with my POST data (at first I thought it was complicated, but here's a perfect example of why doing a little prep work in the beginning is an excellent idea). Anyway, I'm stuck with receiving this type of an array. Over the past couple years, I throw about an hour or two a day at it to try to come up with something better -- I have several solutions that work..... but they all involve looping and either using strpos or preg_match. At the end of each daily 2-hour sessions I spend on this, I end up scrapping my work and reverting to what I have because, at least, my original work never triggers any errors 😃 If you can think of any ideas to point me in the right direction I would appreciate it. The only consistant thing I have to go on is the SKU numbers always are digits, are always 5 digits long, and nothing else in the $_POST variable ever has 5 consecutive digits. I cannot think of any other sure-fire way than to loop through each value, capture those 5 digits, and then find every post variable with the captured 5 digits to then capture the quantity and price. (And, once I have that, the rest of my code is starting to shape up nicely).
  9. My longest post of the year..... (thank you in advance for scrolling 😀) Here is what my $_POST array looks like using print_r($_POST) Array ( [newQuantity77777] => 3 [newPrice77777] => 5.00 [usedQuantity77777] => 1 [usedPrice77777] => 3.99 [total77777] => 18.99 [newQuantity88888] => // sometimes empty [newPrice88888] => [usedQuantity88888] => 4 [usedPrice88888] => 12.00 [total88888] => 48.00 [newQuantity44444] => 2 [newPrice44444] => 4.00 [usedQuantity44444] => 0 [usedPrice44444] => 3.99 [total44444] => 8.00 // these values I don't need [date] => July 25 2021 // these values below I don't need [address] => 123 Anystreet Avenue [address2] => [zipcode] => 90210 [city] => Beverly Hills [state] => CA [planet] => Mars ) I've been trying to use that array to create a special "sub-array" for only the SKU numbers and just their new and used quantities and prices. DESIRED RESULT: Array ( [77777] => Array ( [newQuantity] => 3 [newPrice] => 5.00 [usedQuantity] => 1 [usedPrice] => 3.99 ) [88888] => Array ( [newQuantity] => 0 [newPrice] => 0 [usedQuantity] => 4 [usedPrice] => 12.00 ) [44444] => Array ( [newQuantity] => 2 [newPrice] => 4.00 [usedQuantity] => 0 [usedPrice] => 3.99 ) ) Knowing that my SKU numbers are always exactly 5 digits, and no other $_POST keys will ever have 5 digits, I've been able to accomplish this with horribly convoluted and unsatisfactory code like this: $sku = array(); foreach($_POST as $var => $val) { $number = substr($var,-5); if (preg_match("/\d{5}/",$sku)) { $sku[$number] = // the array keys will be the SKU numbers // then I keep looping to look for the string "newQuantity" // capture that value... and create little mini arrays // for my big multidimensional array..... Is there a better way to go about this? Thank you.
  10. [from php.net]: (PHP 4, PHP 5, PHP 7, PHP) join — Alias of implode() So it's just an alias of implode.... (You did that on purpose! :-)
  11. I know you really do know how to do this in just 1 line.... but, "we earthlings are not yet ready for such knowledge" haha 😃 I like the code -- Thank you, it looks perfect, I'm going to try it now. ...uh-oh.... what's that!...darnit -- that word "join" again... and not even using 2 tables. (Just when I thought I had understood what "join" meant.) Back to my mySQL studybooks I guess. I was going to search the internet again for a function on how to use "array_diff" or "array_intersect" using just keys (If I use json_decode, I have an array keyed with the sku numbers) and then I can intersect it with that simple array. But I see your code already does that! Thank you again!
  12. Perfect! I appreciate the implode and rtrim. And I'll use the "prepared statement" style -- but sometimes I wonder how necessary that is when the values are already sanitized (for example, the SKU numbers I'd be inserting have already been preg_replaced to just digits only, and will only be inserted if exactly 4 digits long, etc.) Interestingly, I am suddenly at a loss how to access a JSON value using json_decode without the "true" (and impossible to search for on the internet because all the search results tell people to use the "true" part). Whenever I try to access the array values of just json_decode($var) I keep getting that error message about std class.
  13. An affiliate marketer refers some products which are stored in a simple array. My website creates a JSON variable of all products sold. $all_items_sold = '{"7777":{"item":"hammer","price":"4.99"},"8888":{"item":"nail","price":"1.99"},"9999":{"item":"apple","price":"2.00"}}'; $referred_by_Affiliate = array('1234','8888','7777'); So, out of all the 3 items that sold, only 2 of them were referred by the affiliate marketer. DESIRED EFFECT: insert this product 8888: $1.99 and insert this product 7777: $4.99 into mysql. Currently I do this: 1.) foreach loop, 2.) use strpos to see if it's in the raw JSON variable. 3.) If there, I use preg_match to find the price. 4.) Do a mySQL insert while still in the foreach loop. Is there a "best practices" way to accomplish this? I'm guessing there is a "one liner" so I don't have to do a foreach loop and using strpos. And I'm guessing there is a way to do multiple mySQL inserts all at once with just one line of code, instead of from inside a foreach loop. This probably can all be accomplished with just one line of code total, error trapping included 😁 Thank you.
  14. Thank you all! I've learned a lot about arrays today (I'm going to learn what this "array_map" thing is that mac_gyver just suggested -- it seems too good to be true). I'm now thinking that my 5000 lines of code really could be reduced to 3 lines 😀
  15. Thank you. But is it still okay to use the " $$ " style? The array loop with the "$$" thing wasn't for mySQL input (the variables are variables used later on in my code). I was just trying to reduce my 5000 lines of code to 4995 lines 😀 That being said, your answer is really amazing -- I didn't realize that feature of PDO. -- I've always wondered why the heck people sometimes put colons before the value names. Now I know. p.s. I'm starting to think you could take my 5000 lines of code, and reduce it down to just 3 lines of code 😀
  16. oops, I did a really terrible typo in my question which changes the whole meaning and desired result and makes my question more stupid than my questions usually are. The 3rd line of code should be $$val = strtoupper($$val); Thanks 😀
  17. I have a long list of named input fields like this: <input name="address"... , <input name="email"... , etc. To minify my PHP code, is there anything syntactically or logically wrong with processing their values like this: $fields = array( 'address' , 'email' , 'phone' , 'city' ); foreach ($fields as $val) { $$val = strtoupper($val); // (or whatever processing I need to do) } //yields $address = processedAddress, $email = processedEmail, $phone = processedPhone, etc. By putting all the word-names into an array, and using " $$ " I only need 4 lines of PHP code to name and process my variables how I want them. This seems to work, but there is a "baaaadddd don't go there " feeling about doing this (maybe PTSD flashbacks from the Register Globals Era), as well as vague recollections of seeing code that uses ${$variable} instead of $$variable. Thank you.
  18. Customer submits their address to receive a prepaid shipping label, then clicks the "Complete Order" button. The return address they input gets validated using PHP, cURL, and a 3rd party validation service. And, of course, I use CSS to lay out the result 😁 Example: the validator suggests a minor change like "avenue" instead of "street." Question: Which of these is "best practice" (and a better visitor experience): a.) Validate behind the scenes and issue the corrected label with NO alerts or fanfare (e.g. the label will the amend "street" to "avenue")? b.) Validate and then re-display the same styled input field layout, but with the corrections highlighted. Included at the bottom, in small font, will be whatever they originally input along with a "checkbox" to override the validator. Then they can click the "Complete Order" button again. c.) Validate, but instead of displaying the same styled input field layout, a brand new layout appears with an "A" and "B" choice (their original input, versus the validated input). Then they choose one of those (either by checkboxing one of them and then clicking "Complete Order," or, by converting the "A" and "B" choices into actual buttons they would click to complete the order. Spending years trying to learn and relearn PHP has destroyed the "user experience" side of my brain 😀 Thank you. Any suggestions would be appreciated.
  19. To disable directory listing, I've found two ways: 1.) ssh command: a2dismod --force autoindex 2.) by editing apache2.conf: <Directory /var/www/> Options -Indexes ........... Which is better? Should I do both? Thank you.
  20. Respectfully, I do understand how rare it can be. And, again, I'm trying to protect myself against what happened when the PHP Freaks Forum got hacked by trying to figure out a way to: a.) Allow customers to be able to retrieve their own data (e.g. "retrieve an invoice or packing slip") b.) Limit access to all data to just one user at one specific computer. To me, protecting against SQL injection seems trivial (in my case, $data = preg_replace( '/[^\d]/ ' , ' ' , $data ); is all I need). However, ever since the day a friend said, "Hey come and look at this," and I saw a file name "PWND" in their root directory, I've been concerned about the issue. I realize this may be beyond the scope of this forum (maybe my question better suits an encryption-related forum), but in my opinion some of the members right here in this forum have the sophistication, the 'outside-the-box' thinking, and the know-how to potentially propose some heretofor undiscovered methodologies. Thank you.
  21. Thank you for your reply. I am trying to prevent (as best as possible) a hacker (who has gained root access) from viewing customer details. From all I've read, it seems incredibly stupid (like way way WAY stupid) to have encryption algorithms that "take 6 billion years to crack," but have the decryption key right there on the server, too. Dumb dumb dumb. And the programmers are "so proud" to have created those 6-billion-year algorithms -- don't they know that if you put the key right there, too, then anyone can read the stuff? According to what I've learned, it appears I only have TWO (2) choices: 1.) If I want customers to be able to "reprint packing slip," I need to have the decryption key right there on the server, too. (Don't steal my car, but the car keys are taped to the windshield) 2.) If I don't want any hacker that has gained root access to read the encrypted files, then my customers won't be able to "reprint packing slip." Hmmmm. wait a minute (wheels always turning in background).... what if each customer had their own password, hashed on my end so they can access their own data? No. That wouldn't work, because the data is still has to be encrypted and you need that decryption key. And if each customer had data that only they could read using a randomly generated key, then I wouldn't be able to read the data.... hmmm. I'm still thinking this is a logic puzzle. Nobody's figured it out yet. I'm going to be the one to figure it out! (with a little Moderator help 😀 )
  22. Customer data is encrypted using OpenSSL, and then stored in mySQL varbinary column on a server. It's now supposedly super safe -- because it can only be read using the secret key hidden right next to it. Question: What if I encrypted that key? And that key could only be decrypted with a passphrase submitted from my own dedicated computer? Then I would be the only one able to read the encrypted customer data on my server, even if that server got hacked. Obviously that would not work, because the server needs the untampered secret key in order to encrypt the data for mySQL. Although this seems insurmountable, it feels more like a logic problem....where if you think about it long enough, the answer will come. Any thoughts on this? Thank you.
  23. Excellent idea. I went through all of my code and switched all of the "if(isset($_POST["value"] && $_POST["value"] != NULL)" to "if(!EMPTY($_POST["value"]))" and it sure cleaned up my code! (However, there was 1 instance where using 'empty' messed things up though... I can't remember what it was right now, but it cleaned up 99% of my code 😀 ) Great idea! (I'm so used to the "which is better, A? or B?" game that I indeed forget to look outside the box for a third solution 😊) So you must be psychic -- just a while ago I was working on the portion of my code that exactly matches your example. I'm wrestling with ternary shorthand trying to figure out how to use "$errors .=" as a string rather than an array "$errors[ ]" This doesn't work: $address = $_POST["address"] ?? $error .= ?: 'Address cannot be blank'; (I can't use $error .= in shorthand I guess) (and I can't google it because .= isn't googlable :-) Thank you. And keeps my code cleaner (e.g instant error messages on un-needed variables. I probably still have at least a dozen unused variables ($someVariable = " ") that I have to find and clean up. I never completely learned PHP and then decided to code. All my thousands of lines of code are all learning experiences that I botch up, then fix, but leave it there in case the fix makes things worse. All my code worked perfectly before Register Globals went out of fashion. Now nothing works 😀 everything is "isset-this" "empty-that" "null-this" "not-equal-that" and then trying to remember if it's better to do !== or just !=................ and now that I'm just starting to get a bit of a handle on all of that, someone comes along and invents "Public-this" "Private-that" "classes," and code with ->arrows in it ..... and now all the modern PHP has backslashes \something\this\that OMG I'll never catch up to all the experts here 😀
  24. 2 PART QUESTION (so I don't have to ask two questions 😀 ) 1.) My script has tons of PHP variables. Is it better to declare them all at the top of my page like this: $cat = $words = $day = $lunch = $user = $address = $potato = $_SESSION["goodpeople"] = $dumbquestionList = $b = $hundredMoreVariables = ""; -or- as needed, like this: $cat = ""; if($day == 'Thursday') { $cat = 'time_to_feed'; } $words = ""; $school = array('teachers'=>'boring','lunch'=>'free'); $words = $school['teachers']; $_SESSION["goodpeople"] = ""; if($_SESSION["goodpeople"] == "" { $_SESSION["goodpeople"] = 'Gandhi'; } 2.) What are the pros and cons of declaring variables as NULL and using " isset " versus declaring variables as "" and using == Example: $cat = $words = $day = $lunch = $user = $address = NULL; if( !isset($cat)) { $cat = 'black'; }.........................if(isset($day)) { $sleep = 'none'; }..............etc., etc. -or- $cat = $words = $day = $lunch = $user = $address = ""; if($cat == "") { $cat = 'black'; }............................ if($day != "") { $sleep = 'none'; }................etc., etc. On my particular coding, I can use either the NULL/isset style, or, the ""/== style, with no errors or ill effects.... but something tells me the expert PHP coders prefer one over the other... Thank you!!
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.