Jump to content
Larry Ullman's Book Forums

bnorcom

Members
  • Posts

    56
  • Joined

  • Last visited

Everything posted by bnorcom

  1. Same page and same image used for each test with only sql different. Parameterized querys have 0 KB size stored but successful one shows KB size in phpmyadmin. Maybe the max value provided should be lowered because it thinks it will be too large so won't even try. <input type="hidden" name="MAX_FILE_SIZE" value="2048000"> <label for="picture">Picture</label> <input name="picture" type="file" id="picture"> $error = chkimg($_FILES['picture'], 'picture'); $thumbnail = buildthumb($_FILES['picture']);} function buildthumb($pic) { $picture = file_get_contents($pic['tmp_name']); $srcimg = imagecreatefromstring($picture); $srcW = imagesx($srcimg); $srcH = imagesy($srcimg); $newW = 80; $newH = 60; $newimg = imagecreatetruecolor($newW,$newH); $x = imagecopyresampled($newimg,$srcimg,0,0,0,0,$newW,$newH,$srcW,$srcH); ob_start(); imageJPEG($newimg); $thumb = ob_get_contents(); ob_end_clean(); return $thumb; }
  2. I can't get the copy/paste function here to work like last time, otherwise I would have pasted some code from the page. The two insert pages are identical except for the two types of sql, and the picture on the first gets successfully inserted, so the thumbnail should be the same in each case. The second-best thing after typing 14 lines of code is to provide a reference I found that does it the same way. It's at www.sum-it.nl/en200319.php. I'll try now and then to copy it but now it's not cooperating.
  3. I appreciate your helping me with my recent questions. I'm working on a "sticky form" page which I got from your previous Web book which has been extremely useful. In your new book I came across your procedural parameterized query teaching. Since I'm working with images, my picture selection below should be large enough. The insert was successful with old-fashioned code (below) but in Internet forums they lecture you against it because of hacking, so I switched to the code I saw in your book. The inserts/updates succeed but a zero-sized mediumblob gets stored. I tried the OOP syntax first, and when that didn't succeed, I tried your procedural approach from the book which again stored everything except the zero-sized blob. Someone on the Internet said there is a maximum mediumblob size specified and that would explain it not wanting to do it for parameterized queries. The fact that it works for a concatenated sql statement might reinforce that. I tried doing my homework but am resorting to asking you another question. It's probably a short but hard to find answer. By the way, a window popped up for copying/pasting the code below which would have been too long to type. <input type="hidden" name="MAX_FILE_SIZE" value="2048000"> <label for="picture">Picture</label> <input name="picture" type="file" id="picture"> $sql = "INSERT INTO products (catid,description,picture,price,quantity,onsale) VALUES ('" .$catid. "','" .$descr. "','" . $thumbnail. "','" .$price. "','" .$quantity. "','" .$onsale. "')"; if ($dbc->query($sql) === TRUE) {echo "Record created successfully";}; $sql = "INSERT INTO products (catid,description,picture,price,quantity,onsale) VALUES (?,?,?,?,?,?)"; $stmt = $dbc->prepare($sql); $stmt->bind_param('isbdii',$catid,$descr,$thumbnail,$price,$quantity,$onsale); $stmt->execute(); if(mysqli_affected_rows($dbc) == 1) {echo "Record created successfully";}; $sql = "UPDATE products SET catid=?,description=?,picture=?,price=?,quantity=?,onsale=? WHERE prodid=?"; $exe = mysqli_prepare($dbc,$sql); mysqli_stmt_bind_param($exe,'isbdiii',$catid,$descr,$thumbnail,$price,$quantity,$onsale,$prodid); mysqli_stmt_execute($exe); if(mysqli_stmt_affected_rows($exe) == 1) {echo "Record updated";};
  4. I tried to keep the original post so brief the explanation was too concentrated to easily decipher it. The showpicture.php parts are: $sql = "SELECT picture FROM products WHERE prodid = $prodid; Then when the row is fetched there is: $picture = $row['picture']; It's sent back with: header("Content-type: image/jpeg"); echo $picture; The page it's successful with has: <img src="showpicture.php?id=<php echo $prodid; ?>">; I figured the sql retrieves the mediumblob image and it may be converted to a jpg when assigned to the variable. It can't be passing a reference as a link because a mediumblob doesn't even have a path to an image because it does not even exist as such. However, it may decide later when it sees the header specifying a jpg that its going to convert it then to binary when it sends/echos it back to the calling program. The caller displays the image properly using what's specified in the <img> tag. It must be transferring the binary image itself, but jQuery is obviously unhappy with what it's receiving, however in the first use without jQuery it works. I was just trying to learn something attempting to make it work with jQuery. Perhaps this is a limitation with jQuery because maybe its not coded for this type of situation.
  5. At first I tried to make it more sophisticated with: var img = New Image(); img.src = data[0]; $('#pic').attr('src',img.src); which showed a box with X for the img tag. Data[0] would be the same as the first element of the array, so I thought it looked more straightforward. I displayed the picture in the page that retrieved the image as well as when it was returned by the jQuery call. But they both showed an exclamation point and not the characters of a binary file. I don't use developer tools because I'm not a developer and I don't want to get in over my head (I just let things develop). It finally dawned on me that JavaScript and PHP are often apples and oranges, but since I'm not into those tools, I'll never know unless someone else knows the secret.
  6. I tried to make my explanation of the situation brief instead of verbose and its hard to get the whole picture. The first test pulls the mediumblob image out of the table, and when it echos it with the proper header, the receiving <img> tag gets the image and displays it, which proves that the computer system part is really powerful (and that a valid image exists in the first place and can be transferred and received as a valid binary file). The page that receives the id request finds one record and one column with $result->fetch_assoc() and that field is put in a variable which is echoed back. I don't know where it quits being a mediumblob and becomes a jpg, but it all works. So I thought why not learn something with jQuery since I already have a working jpg? But somewhere it gets lost when I try to put it into the source attribute of the <img> tag. My first thought is I'm trying to do it the wrong way, or jQuery can't do that kind of thing. By the way, I can't do the copy and paste of text from Notepad using the clipboards in the upper-right of this window. It just doesn't paste something that's been copied to the clipboard.
  7. On page 358 function.js retrieves an image file with var url = 'show_image.php?image=' + image; where the parameter is the file name provided by images.php on page 361 used by create_window as shown on page 356. Show_image.php on page 367 takes that filename, and according to line 45 in the script explained by the text, the "file data itself is sent using the readfile() function . . . to the browser." I have a similar approach where I get an image using <img src="showpicture.php?id=<?php echo $id;?>">. Instead of sending a file name, showpicture.php gets $picture = $row['picture'] from a mediumblob field in MySQL using an id number. It then informs the browser with header("Content-type: image/jpeg") and sends the data on with echo $picture. Readfile($image) and echo $picture both send the binary image file to the browser. In chapter 15 you explain how jQuery is used. I tried using it returning the same image in the Ajax call: $.get( 'showpicture.php', {id: $(this).val()}, function(data) { $('#pic').attr('src',data[0]; }); I know the image exists and is being returned as in the first case, but it fails to display using a jQuery selector. Some people translate the file into base64 to do things, but jQuery should be powerful enough itself. Maybe PHP handles the file better but jQuery is more particular. I sure would appreciate any idea on how to proceed.
  8. I found an answer on the Internet. It said if any of the data contains a quote character it will terminate the input and the remainder of the data will be used as sql instructions. So I implemented mysqli_real_escape_string on the blob and it took out that corruption and stored it properly. I was just assuming that a jpeg was automatically okay. But I suppose that even file_get_contents can insert extraneous stuff.
  9. Instead of moving the file to a folder I created an images table to store the image's attributes similar to what is on page 317. The transfer takes place to the temporary server folder and my code is: $image = $_FILES['picture']; $image_filename = $image['name']; $image_data = file_get_contents($image['tmp_name']); The MySQL query (other fields not included here) uses: $sql = "INSERT INTO images (filename, image_data) VALUES ('{$image_filename}', '{$image_data}')"; The error says "syntax error on line 1." The binary value of the 80X60 image is there in the input when the error data is displayed, and if removed from the sql, the error goes away and the other fields are inserted properly (demonstrating that the overall syntax is okay). It's like it is a corrupted image, but it's a Photoshop jpg. I also tried sql strings with concatenations, plus the parameterized prepare method. It's as if the MySQL processor at my Web host isn't set up for this approach and has no further explanation. The Web host surely has up-to-date MySQL and their ini settings permit uploads. When I ask questions like this I'm lucky if they even understand what I'm asking, and will usually say "we don't debug people's code." Your book doesn't cover storing the raw-data part but it would be the next step if you had enough pages. Thanks for the help.
  10. Used your Script 12.4 on page 362 as an example to test my code at my Web host. Kept getting an SQL error of invalid syntax. Did some research on the Internet and someone's reply had an answer. I'm using the object oriented approach as opposed to the procedural. So the executable part would be: $db = new mysqli (etc.); if($db->query($sql) === TRUE {etc. The last part of the $sql statement in your script would then be: etc. VALUES (0, '" .$title. "', '" .$entry. "'," NOW())"; The PHP engine on my site doesn't like the syntax of a straightforward statement, so you have to separate the variables and include single quotes within quotes so that the variables will be properly surrounded with quotes.
  11. The MySQL code worked just fine. Thought I'd experiment by putting some basic PHP code on an aspx (ASP.Net) page to see if that engine would recognize it. Apparently it's apples and oranges so it's not the same as including it on a html page. Thought using some PHP validation routines on an aspx page might be possible but those two aren't meant to work together.
  12. I see what you were saying. I was trying to figure out the syntax of a PHP SELECT statement and thinking parameters. So I looked in a book and came up with: $query = "SELECT shopname FROM shopper WHERE shopname = ?"; $stmt = $db -> prepare($query); $stmt -> bind_param('s', $name); $stmt -> execute(); $stmt -> bind_result($name); However, I haven't tested it yet on the website so it might not be right yet.
  13. I was just defining the query variable to document it for learning purposes and it won't be executed in code until later. Printing $name in the HTML for "sticky" purposes works easily and putting error messages in it for testing now is expedient whereas later the errors should probably be put in an array and listed. My guess is that filter sanitizing and mysqli escaping probably do the same thing, but using both is extra insurance unless obviously redundant. Also the multiline testing of the variable should probably be put in a function to make it less wordy when there are lots of variables to test.
  14. Two questions: (1) I activated PHP on a site I have at godaddy.com and they said PHP was "vulnerable" and they asked if I wanted to purchase locking software to protect myself when using PHP. I don't need it for testing but I guess a user should know why PHP is vulnerable. (2) I have this code and added MySQL to it. Its probably overkill but for learning it makes sense. $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); if(is_null($name)) { $name = "No name entered"; } elseif ($name === false) { $name = "Invalid name"; } elseif (empty($name)) { $name = "Valid name required"; } else { $query = "SELECT shopname FROM shopper WHERE shopname = '".$name."'"; $name = mysqli_real_escape_string($db, $name); } The sanitize and mysqli environments are probably separate so maybe it takes both to cover all the bases. I don't think someone starting out like myself should make assumptions on what the PHP code actually does until he asks someone does know. Thanks for the feedback.
  15. FILTER_SANITIZE_ STRING strips tags so a browser won't run malicious code. An internet reference said stripslashes is also important. That would mean a backslash would be deleted leaving the character being escaped which wouldn't erase the whole combination. Maybe it would also remove slashes in a malicious directory entry (but then leave unnecessary text). The reference also said to use htmlentities(). If there are cases remaining there would be entities like &abc; created afterwards corrupting the data which is to be stored in a database. Should a regular expression be used to delete any entities (&123;) after running htmlentities()?
  16. No entry in the input field is recognized as being set (but empty) which doesn't seem logical. if (isset($_POST['name'])) { echo "name set to " . $POST['name']; } if (empty($POST['name'])) { echo " empty name"; } $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); if (is_null($name)) { echo "name variable is NULL"; The function is supposed to return NULL if not set but it doesn't happen even with no entry whatsovever. Empty() is true with the digit 0 entered but a space is a valid string and not an empty string (maybe you couldn't even enter an empty string yourself because that's impossible using data entry).
  17. I'm testing the following code on my Web provider's platform: if($_SERVER['REQUEST_METHOD'] == 'POST') { $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); if($name === null) { $name = "No name entered"; } elseif (empty($name)) { $name = "Valid name required"; } elseif ($name === false { $name = "Invalid name"; } else { $name = stripslashes($name); $name = htmlentities($name, ENT_QUOTES); } With testing it recognizes a valid name and a non-existent (empty) one. But I cannot create an input which should be recognized as null or invalid. The filter is supposed to return false if it is an invalid string or null if no entry has been created. Either the coding for the test results is incorrect or the function is no working correctly. Thanks for the help in ironing this out.
  18. My web host uses PHP v.5.4.9 so I can't use isset($_POST['name']) directly and have to create a variable for the test. One person said that its best to create variables to work with at the start for every form field anyway instead of using the POST input field itself. Writers say that client-side validation is for the client's benefit and the required attribute of HTML5 or jQuery is useful. But they say that server-side checking is crucial because JavaScript is easily circumvented by malicious activity. One writer said you should allow a zero or space in a required field to say that something has been typed in avoiding an error message. He said that strlen() would detect that and pass it up as an error. However, empty() reports that a zero is a missing value, but it recognizes that a space makes it not empty. So if trim() was used purging a white space, the filler to satisfy a requirement would be removed and the purpose would be defeated. Maybe its a bad idea to give the client tricks to use. One writer showed where "malicious JavaScript code" could be placed in an entry creating a SQL injection attack. He used htmlentities() to produce named entity replacements but then said they were placed as "output to the client browser not being considered part of the markup." Does that mean that the malicious code in <script> tags became neutralized by htmlentities()?
  19. The previous template is for strings so this would be one for integers. Since it is form processing my assumption would be that since you know it's a form the coding made especially for it should be used instead of a more generic pattern. An example would be: $age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT); if(is_null($age) || $age === false)) { $error = 'error'; } A more convenient variable is created to work with. No trim() is necessary because the function probably doesn't care about white space. The variable content exists if it is a valid integer. A null result means there is nothing there at all. If it tests as false it means it is an invalid integer. It doesn't seem necessary to sanitize anything since passing the test means it is okay. This pattern would work for numbers but emails or passwords in strings would require more sophisticated processing. Here filter_var wasn't used at all because of filter_input. My original post wondered whether there were so many ways of doing it that only a lot of trial and error and experimentation would be required to get to the point of making it easier. These two examples seem straightforward such that a person wouldn't have to buy more books just to find out the right way of doing it from the experts.
  20. Came across an example for a string: $name = trim($_POST['name']); $set = isset($name); if($set) { if(strlen($name) == 0 { $name = ""; } } else $name = ""; So this would be a pattern for every string. First determine if there is form data for it and get rid of white space at the same time. Then if it is there see if it has characters by calculating its length (and allowing a zero even if its a required field). If nothing qualifies create an error message. The field has been converted so you work with the variable. You would treat every string field the same way and not have to recode it differently each time because all the important bases would be covered by the pattern instead of having to reinvent one every time.
  21. Have done some reading and for starters when if($_SERVER['REQUEST_METHOD'] == 'POST') is used the form data arrives at PHP as strings. Sanitize filters only seem to remove tags, and validate filters only seem to validate. Since white space is not good it seems like you'd always use trim() first on everything. Then the filter functions convert the value to the required type or null if invalid. Some programs create variables right away like $name = trim($_POST['name']). Then there's filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING) which returns and creates a variable. It doesn't need one previously defined which saves a statement and seems to provide better documentation than filter_var. Also maybe SANITIZE can replace htmlentities() due to FILTER_SANITIZE_SPECIAL_CHARS. There must be a straightforward approach to all this so each step isn't "it seemed like a good idea at the time."
  22. Server-side validation is necessary for form data. For this, Script 12.8 uses htmlentities(). Also in the script is strip_tags(). To complicate things on page 328 is htmlspecialchars(). Then if you dig around you find filter_input() and filter_var(). Also there's filter_validate() and filter_sanitize(). To be thorough do you have to use all these to make sure nothing is overlooked?
  23. The successive posts show how I was working it out step by step. The last one is simple and it works, so I would use it this way and don't have any more questions.
  24. I tried to paste a short example of code from a text file so I didn't have to type it all in but the paste options in the header don't work and the method of getting it from the clipboard doesn't work either. Without an example accompanying the forum question there isn't enough information for someone to adequately answer.
  25. On page 8 RE Script 1.2 it says "create a new PHP document to be named phpinfo.php. Begin the page with <?php." On page 16 it says "begin a new HTML document to be named hello1.php." Throughout the book examples start as the latter but are called .php scripts. Since Script 1.3 has much "hard-coded HTML" it could have been created as a html doc and the interpreter would have processed <?php statements within it anyway. But if they are PHP scripts wouldn't it be better documentation to start the page with <?php instead of <!doctype html>?
×
×
  • Create New...