so I am just learning PHP and am trying to make it so you can upload a picture. When attempting this on a local host all I get is a picture of a piece of paper being ripped in half (it must be some error/replacement picture). The directory for the image is right its just not being displayed properly. thanks
Code:
<?php
//connect to the database
$link = mysql_connect("localhost", "root", "root")
or die("Could not connect: " . mysql_error());
mysql_select_db("images", $link)
or die (mysql_error());
//make variables available
$image_caption = $_POST['image_caption'];
$image_username = $_POST['image_username'];
$image_tempname = $_FILES['image_filename']['name'];
$today = date("Y-m-d");
//upload image and check for image type
//make sure to change your path to match your images directory
$ImageDir ="/Users/JohnSmith/Desktop/images/";
$ImageName = $ImageDir . $image_tempname;
if (move_uploaded_file($_FILES['image_filename']['tmp_name'],
$ImageName)) {
//get info about the image being uploaded
list($width, $height, $type, $attr) = getimagesize($ImageName);
switch ($type) {
case 1:
$ext = ".gif";
break;
case 2:
$ext = ".jpg";
break;
case 3:
$ext = ".png";
break;
default:
echo "Sorry, but the file you开发者_如何学编程 uploaded was not a GIF, JPG, or " .
"PNG file.<br>";
echo "Please hit your browser's 'back' button and try again.";
}
//insert info into image table
$insert = "INSERT INTO images
(image_caption, image_username, image_date)
VALUES
('$image_caption', '$image_username', '$today')";
$insertresults = mysql_query($insert)
or die(mysql_error());
$lastpicid = mysql_insert_id();
$newfilename = $ImageDir . $lastpicid . $ext;
rename($ImageName, $newfilename);
}
?>
<html>
<head>
<title>Here is your pic!</title>
</head>
<body>
<p>Here is the picture you just uploaded to our servers:</p>
<img src="Users/AdamAshwal/Desktop/images/<?php echo $lastpicid . $ext; ?>" align="left">
<strong><?php echo $image_name; ?></strong><br>
This image is a <?php echo $ext; ?> image.<br>
It is <?php echo $width; ?> pixels wide
and <?php echo $height; ?> pixels high.<br>
It was uploaded on <?php echo $today; ?>.
</body>
</html>
The image isn't being shown because your Desktop is not a public webroot. Make a directory within your app to store the uploaded images and render them from there.
JMC Creative's answer is correct, too -- your image tags don't seem to be looking in the right place for the uploaded images.
On a side note, you have a very obvious SQL injection vulnerability in the code sample that you provided. All user inputs that are being stored in the database should be sanitized with mysql_real_escape_string
. See this XKCD comic for a humorous explanation. An example follows:
$image_caption = mysql_real_escape_string($_POST['image_caption']);
Shouldn't your image src be:
<img src="/Users/JohnSmith/Desktop/images/<?php echo $lastpicid . $ext; ?>">
The src should be relative to where the script is.
And don't use align="left"
in the html tag, use css instead please.
精彩评论