Jump to content
Larry Ullman's Book Forums

Problem With Chapter 19 Uploading And Viewing Files


Recommended Posts

After exhausting searching and trying many different things and asking people about the add_print.php script in chapter 19 I am now positive that there are errors in this script. I have tried using the exact script supplied by the author in his working files and the images don't display in my uploads folder, and they also don't show up in my view_print.php page. 

 

I put the entire script up on stack overflow and got an answer that partially helped fix this. I however still don't see the images on my view_print pages. The show_image.php isn't doing it's job like it should, and I am using the exact files provided by the author. This is extremely frustrating and time consuming, one would expect the examples to be error free.

 

Here is the fix  I got on stack overflow. 

 

You need to add a couple lines of code and change one line to actually display the image in your uploads folder. The entire modified script is below. Note that this doesn't entirely fix the problem though, you still don't see the images on the view_print.php page.

$path_parts = pathinfo($_FILES["image"]["name"]);
$extension = $path_parts['extension'];
 
$id = mysqli_stmt_insert_id($stmt); // Get the print ID.
rename ($temp, "../../../uploads/$id.".".$extension");
 
 
<?php # Script 19.2 - add_print.php
// This page allows the administrator to add a print (product).
 
require ('../../mysqli_connect.php');
 
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form.
 
// Validate the incoming data...
$errors = array();
 
// Check for a print name:
if (!empty($_POST['print_name'])) {
$pn = trim($_POST['print_name']);
} else {
$errors[] = 'Please enter the print\'s name!';
}
 
// Check for an image:
if (is_uploaded_file ($_FILES['image']['tmp_name'])) {
 
// Create a temporary file name:
$temp = '../../../uploads/' . md5($_FILES['image']['name']);
 
// Move the file over:
if (move_uploaded_file($_FILES['image']['tmp_name'], $temp)) {
 
echo '<p>The file has been uploaded!</p>';
 
// Set the $i variable to the image's name:
$i = $_FILES['image']['name'];
} else { // Couldn't move the file over.
$errors[] = 'The file could not be moved.';
$temp = $_FILES['image']['tmp_name'];
}
 
} else { // No uploaded file.
$errors[] = 'No file was uploaded.';
$temp = NULL;
}
 
// Check for a size (not required):
$s = (!empty($_POST['size'])) ? trim($_POST['size']) : NULL;
 
// Check for a price:
if (is_numeric($_POST['price']) && ($_POST['price'] > 0)) {
$p = (float) $_POST['price'];
} else {
$errors[] = 'Please enter the print\'s price!';
}
 
// Check for a description (not required):
$d = (!empty($_POST['description'])) ? trim($_POST['description']) : NULL;
 
// Validate the artist...
if ( isset($_POST['artist']) && filter_var($_POST['artist'], FILTER_VALIDATE_INT, array('min_range' => 1))  ) {
$a = $_POST['artist'];
} else { // No artist selected.
$errors[] = 'Please select the print\'s artist!';
}
 
if (empty($errors)) { // If everything's OK.
 
// Add the print to the database:
$q = 'INSERT INTO prints (artist_id, print_name, price, size, description, image_name) VALUES (?, ?, ?, ?, ?, ?)';
$stmt = mysqli_prepare($dbc, $q);
mysqli_stmt_bind_param($stmt, 'isdsss', $a, $pn, $p, $s, $d, $i);
mysqli_stmt_execute($stmt);
 
// Check the results...
if (mysqli_stmt_affected_rows($stmt) == 1) {
 
// Print a message:
echo '<p>The print has been added.</p>';
 
// Rename the image:
$path_parts = pathinfo($_FILES["image"]["name"]);
$extension = $path_parts['extension'];
$id = mysqli_stmt_insert_id($stmt); // Get the print ID.
rename ($temp, "../../../uploads/$id.".".$extension");
 
// Clear $_POST:
$_POST = array();
 
} else { // Error!
echo '<p style="font-weight: bold; color: #C00">Your submission could not be processed due to a system error.</p>'; 
}
 
mysqli_stmt_close($stmt);
 
} // End of $errors IF.
 
// Delete the uploaded file if it still exists:
if ( isset($temp) && file_exists ($temp) && is_file($temp) ) {
unlink ($temp);
}
 
} // End of the submission IF.
 
// Check for any errors and print them:
if ( !empty($errors) && is_array($errors) ) {
echo '<h1>Error!</h1>
<p style="font-weight: bold; color: #C00">The following error(s) occurred:<br />';
foreach ($errors as $msg) {
echo " - $msg<br />\n";
}
echo 'Please reselect the print image and try again.</p>';
}
 
// Display the form...
?>
<h1>Add a Print</h1>
<form enctype="multipart/form-data" action="add_print.php" method="post">
 
<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
 
<fieldset><legend>Fill out the form to add a print to the catalog:</legend>
 
<p><b>Print Name:</b> <input type="text" name="print_name" size="30" maxlength="60" value="<?php if (isset($_POST['print_name'])) echo htmlspecialchars($_POST['print_name']); ?>" /></p>
 
<p><b>Image:</b> <input type="file" name="image" /></p>
 
<p><b>Artist:</b> 
<select name="artist"><option>Select One</option>
<?php // Retrieve all the artists and add to the pull-down menu.
$q = "SELECT artist_id, CONCAT_WS(' ', first_name, middle_name, last_name) FROM artists ORDER BY last_name, first_name ASC";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) > 0) {
while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
echo "<option value=\"$row[0]\"";
// Check for stickyness:
if (isset($_POST['artist']) && ($_POST['artist'] == $row[0]) ) echo ' selected="selected"';
echo ">$row[1]</option>\n";
}
} else {
echo '<option>Please add a new artist first.</option>';
}
mysqli_close($dbc); // Close the database connection.
?>
</select></p>
 
<p><b>Price:</b> <input type="text" name="price" size="10" maxlength="10" value="<?php if (isset($_POST['price'])) echo $_POST['price']; ?>" /> <small>Do not include the dollar sign or commas.</small></p>
 
<p><b>Size:</b> <input type="text" name="size" size="30" maxlength="60" value="<?php if (isset($_POST['size'])) echo htmlspecialchars($_POST['size']); ?>" /> (optional)</p>
 
<p><b>Description:</b> <textarea name="description" cols="40" rows="5"><?php if (isset($_POST['description'])) echo $_POST['description']; ?></textarea> (optional)</p>
 
</fieldset>
 
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
 
</form>
 
</body>
</html>

 

Link to comment
Share on other sites

The scripts as in the book and in the downloads do work as is. You shouldn't have to change anything to get them to work (except as where specifically mentioned in the book). If you're having problems with this script, let me know what they are (in detail) and I can help you debug them. 

Link to comment
Share on other sites

Hi Larry

Here is the trouble I am having with the script add_print.php, browse_prints.php, and view_print.php.

For add_print.php, when I use your scripts from this site modified with my database settings and changed so that they point to my uploads folder, when I upload a jpg image or other type of image, the file goes to my uploads folder, but it appears as  a blank file, when I look at the properties of the file it calls it type "file". When I added 2 lines of my own code and changed a third line to it I can view the images in my uploads folder, without the 2 lines of code it is impossible, I don't see them. Here are the 3 lines of code. 

$path_parts = pathinfo($_FILES["image"]["name"]);

$extension = $path_parts['extension'];
rename ($temp, "../../../uploads/$id.".".$extension");
 
For view_print.php and browse_prints.php , I don't see the images I uploaded when I click on the links to the images on browse_prints.php. It says image unavailable. Yet I know they are there. 
 
Could it be because I am running Windows 8.1?
I have spent several hours trying different things and nothing works. 
Link to comment
Share on other sites

Okay, as I replied in your other post on this same issue, it's fine that your images on the file system appears as a blank file and has a property type of "file". The uploaded images won't be accessed through the file system, so those properties are meaningless. Aside from confirming that the files get uploaded and renamed, don't worry about looking at the files on the file system. That's not how they're meant to be accessed.

 

And to put a finer point on it, you don't want to add those other lines of code, because those will break the scripts that actually use the uploaded file.

 

The real issue is if they're not appearing in the view_print.php page. What you should do, which I think I suggest in the book, is run the source code of the img tag directly in your browser to confirm what's happening with the script that retrieves and displays the image. 

Link to comment
Share on other sites

Hi 

I have done that already, I am following your book to the letter, it just takes me to the view_print.php page where it says the image is unavailable. So what now?

here is a part of the source code. 

 

td align="left"><a href="browse_prints.php?aid=1">Graham David Rodrigue</a></td>
<td align="left"><a href="view_print.php?pid=66">best2233</a></td>
<td align="left">ss</td>
<td align="right">$22.00</td>
</tr>
<tr>
<td align="left"><a href="browse_prints.php?aid=1">Graham David Rodrigue</a></td>
<td align="left"><a href="view_print.php?pid=65">best99</a></td>
<td align="left">ss</td>
<td align="right">$22.00</td>
</tr>
<tr>
<td align="left"><a href="browse_prints.php?aid=1">Graham David Rodrigue</a></td>
<td align="left"><a href="view_print.php?pid=63">bestr77</a></td>
<td align="left">ss</td>
<td align="right">$22.00</td>
Link to comment
Share on other sites

Well, I'll help whether you buy the books or not, because that's why I have these forums. But I do appreciate the interest in the books. 

 

The source code you've provided is part of browse_prints.php, which is working, correct? If the problem is on view_prints.php, I'd need to see some of that source code. Specifically the source code for the HTML img tag.

  • Upvote 1
Link to comment
Share on other sites

Hi

Here is the source code from view_prints.php. I don't see an image tag, it just says No Image Available.

 

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>best2233</title>
</head>
 
 
<body>
<table cellspacing="0" cellpadding="0" border="0" align="center" width="600">
<tr>
<td align="center" colspan="3"><img src="images/title.jpg" width="600" height="61" border="0" alt="title" /></td>
</tr>
<tr>
<td><a href="index.php"><img src="images/home.jpg" width="200" height="39" border="0" alt="home page" /></a></td>
<td><a href="browse_prints.php"><img src="images/prints.jpg" width="200" height="39" border="0" alt="view the prints" /></a></td>
<td><a href="view_cart.php"><img src="images/cart.jpg" width="200" height="39" border="0" alt="view your cart" /></a></td>
</tr>
<tr>
<td align="left" colspan="3" bgcolor="#ffffcc"><br />
</body>
</html><div align="center">
<b>best2233</b> by 
Graham David Rodrigue<br />22<br />$22.00 
<a href="add_cart.php?pid=66">Add to Cart</a>
</div><br /><div align="center">No image available.</div>
<p align="center">ss</p><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
 
<body>
<!-- Script 19.4 - footer.html -->
<br /></td>
</tr>
<tr>
<td align="center" colspan="3" bgcolor="#669966"><font color="#ffffff">©Copyright...</font></td>
</tr>
</table>
</body>
</html>
Link to comment
Share on other sites

Okay, so to debug this...if you're getting that result, that means this conditional is false:

if ($image = @getimagesize ("../uploads/$pid")) {

So the next step would be to debug that conditional. I'd start by verifying the value of $pid and that it's location is correct relative to this script. You can also remove the @ to see any errors that occur.

  • Upvote 1
Link to comment
Share on other sites

Hi

sorry for not understanding, but after trying countless things in the past 45 minutes I am getting nowhere. I am not sure how to verify the location of $pid relative to the script. I mean I am using the file downloaded from the working files in this forum. I just changed the uploads path and the connection. I checked show_image.php too and don't know what else to check. I removed the @ and this is the error it gives me. 

 

Warning: getimagesize(../../../../uploads/62): failed to open stream: No such file or directory inD:\xampp\htdocs\larry\chapter19\view_print.php on line 36

No image available.
Link to comment
Share on other sites

I advanced a bit, now I atleast managed to get the unavailable image to display for 2 prints, with the others I am still getting the same error message I put in my previous post. Here is the source code with the image tag which appears now. Please let me know how to make it work. thanks for your help.

 

<div align="center">   <b>php</b> by   Graham David Rodrigue<br />u<br />$66.00   <a href="add_cart.php?pid=85">Add to Cart</a>   </div><br /><div align="center"><img src="show_image.php?image=85&name=php_mysql_logo.png" width="321" height="186" alt="php" /></div>   <p align="center">(No description available)</p><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml">   <head>   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   <title>Untitled Document</title>   </head>
Link to comment
Share on other sites

You verify the value of $pid by just printing it out. But the error message clearly indicates the problem: your path is wrong. Where did you put the uploads folder?

 

You can also get to another debugging step by loading show_image.php?image=85&name=php_mysql_logo.png directly in your browser to see the result. You'll need to preface that with the actual URL (http://localhost/path/to/ or whatever). 

  • Upvote 1
Link to comment
Share on other sites

  • 2 months later...

Hello!  I too have been having the same problem and have been searching everywhere to find out what the issue is.  I am hoping that maybe you can help as well :).

 

I was having the exact same problem and after reading this thread tired to debug my path, and I was finally able to get something to show, though it was the "Image Not Available" image.  This was huge progress for me, but I am still stuck since the actual image I need to display is not showing and I am at a loss to get it to display.

 

Apparently I am calling the image incorrectly?  I know that it is looking in the right folder, and it is looking for the appropriate file and even though there is one in there by that name, it is showing the "Image Not Available" image instead....

Link to comment
Share on other sites

Yeah, I'd start by printing out the full name and path of the image that the script is trying to load. You can share that with us here, along with the actual path to the image on your computer, where the script is, etc. 

Link to comment
Share on other sites

Thank you for your reply Larry :).

 

Okay, so the full name and path that the script is trying to load is:  

 

This is what my source code is showing: <img src="show_image.php?image=1" />

 

The image is on my hosting server. The path is: /test1/ksanford/uploads/ and I have also tried ../../../../../uploads .  I have actually tried many variations on the path to see if it may be up or down a few folders in how it was reading it, but alas I still keep getting the same results.  I do have a picture in the uploads folder by the name "1".

 

The files are a bit deep, because I was practicing on a current site, but this is my file path to get to the script:

test1/ksanford/public_html/test/test/ch19/show_image.php

Link to comment
Share on other sites

Oops :D  I just realized that I pasted the code that I stripped down to try to find out if the problem was at the core.  Here is my code that I should be using.

 

This is what the source code is showing:

<img src="show_image.php?image=1&name=61166_199051356922191_191998974_n.jpg" width="466" height="700" alt="Travel" />

 

And my image path in the script is: 

$image = 'test1/ksanford/uploads/' . $_GET['image']

 

Now that I have gone back to the original code again it is doing something different, so I know I am getting closer.  It is displaying the "Image Not Available" image in the size of the actual image.  So it is changing with each print.  I know that I am getting close to finding what the problem is, but as of yet have not found it...

Link to comment
Share on other sites

 Share

×
×
  • Create New...