Jump to content

uploading a picture


Matpatnik

Recommended Posts

Hi guys,I'm trying to build an upload picture form somthing very simple for now.here is my code:

<?php	// connection to MySQL	$connect = mysql_connect("localhost","****","****")		or die ("Hey loser, check you connection.");		// make sure we're using the right database	mysql_select_db("****");			// make variable available	$item_caption = $_POST['item_caption'];	$image_username = $_POST['image_username'];	$image_tempname = $_FILES['image_filename']['name'];	$today = date("Y-m-d");	$imageDir = "images/";		if (($_FILES["file"]["type"] == "images/gif") 	  || ($_FILES["file"]["type"] == "images/jpeg")	  && ($_FILES["file"]["size"] < 800000)) {		if ($_FILES["file"]["error"] > 0) {			echo "Return Code: " . $_FILES["file"]["error"] . "<br />";		} else {			echo "Upload: " . $_FILES["file"]["name"] . "<br />";			echo "Type: " . $_FILES["file"]["type"] . "<br />";			echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";			echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";			if (file_exists($imageDir . $_FILES["file"]["name"])) {				echo $_FILES["file"]["name"] . " already exists. ";			} else {				move_uploaded_file($_FILES["file"]["tmp_name"],				$imageDir . $_FILES["file"]["name"]);				echo "Stored in: " . $imageDir . $_FILES["file"]["name"];			}		}	} else {		echo "Invalid file";	}	$ImageName = $imageDir . $image_tempname;				// insert info into image table		$insert = "INSERT INTO images				   (images_name, images_date)				   VALUES				   ('$item_caption', '$today')";		$insertresult = mysql_query($insert)			or die(mysql_error());				$lastpicid = mysql_insert_id();				$newfilename = $imageDir . $lastpicid . $ext;				rename($ImageName, $newfilename);?>

and I get this error:

Invalid fileWarning: rename(images/,images/4) [function.rename]: Invalid argument in /home/***/public_html/test/check_image.php on line 53
Did I forgot something?
Link to comment
Share on other sites

Invalid fileWarning: rename(images/,images/4)
You're trying to rename the folder "images/" to "images/4". It doesn't like that. You're also using both $_FILES['image_filename'] and $_FILES['file'], and the variable $ext is undefined.
Link to comment
Share on other sites

Hi rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt"); to rename file you have to specify sorce and destination with file name with extension.. now plz look carefully in ur error you will get the tings whats the error Regards,Vijay

Link to comment
Share on other sites

Ok I did fix it by modifying the code abit

$today = date("Y-m-d");$i_username = $_POST['username'];$i_nname = $_POST['image_name'];$i_name = $_FILES['file']["name"];$i_type = $_FILES['file']["type"];$i_size = ($_FILES['file']["size"] / 1024);$i_tname = $_FILES['file']["tmp_name"];$i_error = $_FILES['file']["error"];$i_folder = "images/";	// image directory$i_dir = $i_folder . $i_name;if ($i_type == "image/gif") {	$ext = ".gif";} else if ($i_type == "image/jpeg") {	$ext = ".jpeg";} else if ($i_type == "image/png") {	$ext = ".png";}if (($i_type == "image/gif")|| ($i_type == "image/jpeg")|| ($i_type == "image/png")&& ($i_size < 20000)) {	if ($i_error > 0) {		die("<span style=\"color:#FF0000\">Return Code: " . $i_error . "</span>");	} else {		echo "Upload: " . $i_name . "<br />";		echo "Database picture name: " . $i_nname . "<BR>";		echo "Type: " . $i_type . "<br />";		echo "Size: " . round($i_size) . " Kb<br />";		echo "Temp file: " . $i_tname . "<br />";		if (file_exists($i_dir)) {			die("<span style=\"color:#FF0000\">" . $i_name . " already exists. Change the name and try again</span>");		} else {			move_uploaded_file($i_tname, $i_dir);			echo "Stored in: " . $i_dir . "<br>";

and it work fine now but, I got this code which is smaller and cleaner

	// make variable 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	$ImageDir = "images/";	$ImageThumb = $ImageDir . "thumbs/";	$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);

My problem with this one it's not passing through the first if statement! It look like the same as the other one but shortened a bit more, isn't? I can't see why it dosen't work :) Any idea?

Link to comment
Share on other sites

You need to figure out why move_uploaded_file is failing. Print both the source and destination filenames to see what you are asking it to do, and use this on the top to enable warnings and notices:ini_set("display_errors", 1);error_reporting(E_ALL);

Link to comment
Share on other sites

Ok it show me: array(0) {}How come? here is the form:

<form name="form1" method="post" action="check_image.php" enctype="multipart/form-data">	  <table border="0" cellpadding="5">	  <tr>		  <td>Picture Title</td>		<td><input name="image_caption" type="text" id="image_caption" size="55" maxlength="255"></td>	  </tr>	  <tr>		  <td>Your Username</td>		<td><input name="image_username" type="text" id="image_username" size="15" maxlength="255"></td>	  </tr>	  <tr>		  <td>Upload Image</td>		<td><input name"image_filename" type="file" id="image_filename"></td>	  </tr>	</table>	<br>	<em>Acceptable image include: GIF, JPG/JPEG, and PNG.</em>	<p align="center">	  <input type="submit" name="Submit" value="Submit"> <input type="reset" name="Submit2" value="Clear Form">	</p>  </form>

When submit doesn't it take the input name="" to define the $_POST or $_FILES ?

Link to comment
Share on other sites

<tr> <td>Upload Image</td> <td><input name"image_filename" type="file" id="image_filename"></td> </tr>
I forgot the = sign in between name and " :) Thank you for your help
Link to comment
Share on other sites

I have to ask a question here now...is it possible to upload pictures to a database (MySQL) instead of a folder called for example images? Because I have a news system, and I'm gonna save with pictures, and when my PHP codes takes out from the database, it should be an image with out, and I want to do that as simple as use: echo "<img src='$row[id]' alt='' />"; if that's possible...

Link to comment
Share on other sites

Yes it is possibleThere is a big discussion about should we or not but the easiest way of doing it is with the folder (for me as a newbie). You can store 100px * 100px .gif thumbnails in the database using longblob, it will transfer your picture into binary but then you will have to convert it into whatever format you want to show it.With the folder you can store the path of the picture or rename it and using the 'id' in your database table to get it back on your page.I hope that help you :)

Link to comment
Share on other sites

Okay.When I add news into my database, each news will automaticlly get an ID number. If I upload a picture to the database, can that image automatically be renamed to for example 1.jpg if this is the first news, because then it'll get the ID number 1. Then I also want the images to be renamed to the same as the ID it's under.I bet you won't understand, cause our English teacher sucks, so we don't learn too much :)

Link to comment
Share on other sites

I want to do that as simple as use: echo "<img src='$row[id]' alt='' />"; if that's possible...
It's not that simple. You can store any file in a database using a binary data type for the field (such as blob). But you are storing the binary data. So, for a 50kb jpg file, you are storing 50kb of binary data. If you just do this:echo "<img src='{$row['data']}' alt='' />";Then you print out 50kb of binary data for the "src" attribute, and the src attribute needs to be a filename, not a huge data stream. What you need to do is have the src attribute point to a PHP page that gets the file from the database and sends it like it should be sent. So the img tag would look like this:echo "<img src='get_picture.php?id={$row['id']}' alt='' />";The get_picture.php page would need to get the ID from the querystring, look up the record in the database, and use the content-type, content-disposition, and content-length headers to output the data as an image.
<?php$id = intval ($_GET['id']);$result = mysql_query("SELECT * FROM images WHERE id={$id}");$row = mysql_fetch_assoc($result);header("Content-type: image/jpeg");header("Content-disposition: attachment; filename=\"image.jpg\"");header("Content-length: " . strlen($row['data']));echo $row['data']; //send the file data?>

That's a simplified example that doesn't do any error checking and only output jpg files, but that's the idea.

Link to comment
Share on other sites

I'm actually working on something similar

$today = date("Y-m-d");$i_username = $_POST['username'];$i_nname = $_POST['image_name'];$i_name = $_FILES['file']["name"];$i_type = $_FILES['file']["type"];$i_size = ($_FILES['file']["size"] / 1024);$i_tname = $_FILES['file']["tmp_name"];$i_error = $_FILES['file']["error"];$i_folder = "images/";	// image directory$i_dir = $i_folder . $i_name;if ($i_type == "image/gif") {	$ext = ".gif";} else if ($i_type == "image/jpeg") {	$ext = ".jpeg";} else if ($i_type == "image/png") {	$ext = ".png";}if (($i_type == "image/gif")|| ($i_type == "image/jpeg")|| ($i_type == "image/png")&& ($i_size < 20000)) {	if ($i_error > 0) {		die("<span style=\"color:#FF0000\">Return Code: " . $i_error . "</span>");	} else {		echo "Upload: " . $i_name . "<br />";		echo "Database picture name: " . $i_nname . "<BR>";		echo "Type: " . $i_type . "<br />";		echo "Size: " . round($i_size) . " Kb<br />";		echo "Temp file: " . $i_tname . "<br />";		if (file_exists($i_dir)) {			die("<span style=\"color:#FF0000\">" . $i_name . " already exists. Change the name and try again</span>");		} else {			move_uploaded_file($i_tname, $i_dir);			echo "Stored in: " . $i_dir . "<br>";						// insert info into image table			$insert = "INSERT INTO images					  (images_name, images_username, images_date)					  VALUES					  ('$i_nname', '$i_username', '$today')";			$insertresult = mysql_query($insert)				or die(mysql_error());					$newname = $i_folder . mysql_insert_id() . $ext;			rename($i_folder . $i_name, $newname);						echo "new name: " . $newname;		}	}} else {	echo "<span style=\"color:#FF0000\">Invalid file or your file is too big</span>";}

This is my draft code, it work well on my server, it only accept gif, jpeg/jpg, and png format. It will rename using the 'images_id'. You will need a table called images with row image_id, images_name, images_username, images_date. And this is the form that come with it

<?php $trest = "Username";$header=<<<TEST<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>Untitled Document</title></head>TEST; $body=<<<TEST<body><form action="upload_file.php" method="post" enctype="multipart/form-data">  <table>	<tr>	  <td>You are loged as </td>	  <td>$trest<input name="username" type="hidden" id="username" value="$trest" /></td>	</tr>	<tr>	  <td>Picture Title</td>	  <td><input name="image_name" type="text" id="image_name" size="30" maxlength="255" /></td>	</tr>	<tr>	  <td>Filename:</td>	  <td><input type="file" name="file" id="file" size="30" /></td>	</tr>	<tr>	  <td align="center" colspan="2"><input type="submit" name="submit" value="Submit" />	   <input type="reset" name="submit2" value="Reset" /></td>	</tr>  </table></form></body></html>TEST;echo $header . $body;?>

Play with it and have fun :)/* edited */* I forgot to tell you that you will need to have a folder called images in the same folder that those files are and you will need to chmod them to be able to rewrite it and store it I've used 0777 for now but I strongly suggest that you secure those files unless you can have bad surprise (unwanted user that throw 2k pictures every day)

Link to comment
Share on other sites

My tester server have a php version 4.4.3 does it handle the function imagefilter()? because I got this error message:

Fatal error: Call to undefined function: imagefilter() in...
with this code:
	// make variables available	$id = $_POST['id'];	if (isset($_POST['bw'])) {		$bw = $_POST['bw'];	} else {		$bw = '';	}		// get info on the pic we want	$getpic = mysql_query("SELECT * FROM images WHERE images_id = '$id'")		or die(mysql_error());	$rows = mysql_fetch_array($getpic);	extract($rows);		$image_filename = "images/" . $images_id . ".jpg";		list($width, $height, $type, $attr) = getimagesize($image_filename);		$image = imagecreatefromjpeg("$image_filename");		if ($bw == 'on') {		imagefilter($image, IMG_FILTER_GRAYSCALE);	}

Link to comment
Share on other sites

Thank you guys, your help are very appreciatedI've send a tickets to my host to upgrade the php to 5.2.0 and MySQL to 5.0.27. Now I just have to wait till the upgrade is done :)

Link to comment
Share on other sites

  • 3 weeks later...

Hi guys I got this error now:

Warning: move_uploaded_file(../images/6) [function.move-uploaded-file]: failed to open stream: Is a directory in /usr/local/1/2/3/4/5/6/age.php on line 40Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phprgnmcn' to '../images/6' in /usr/local/1/2/3/4/5/6/age.php on line 40
I think I know where the error come from, it's the (../) which it doesn't like. How do you set the path to go out of the folder?Like when you are in mysite.com/images/something/here.php and want to go back to mysite.com/.In html it's easy it's just ../ to go back to the root folder but how is it done with php (if it's the error)
Link to comment
Share on other sites

I don't think you can use relative paths with move_uploaded_file, because you are not moving a file in the same directory as the PHP script, the file is in another directory. It lists the file as /tmp/phprgnmcn, and trying to move it to ../images I think would try to move it to /images/ in the root, not an images folder in the web directory. You can check in $_SERVER['DOCUMENT_ROOT'] and see if that path will help you out.

Link to comment
Share on other sites

When I was using /images/ it uploaded into the same folder that I was like if i was in this/ then I would need a folder this/images/ to store the image.By using the whole path wouldn't add it to this/ ?edited: It give me the same error but with the whole path, here is my code:

$ImageDir = $_SERVER['DOCUMENT_ROOT'] . "/images/" . $_POST['image_section'];			// upload image and check for image type		if (move_uploaded_file($_FILES['image_filename']['tmp_name'], $ImageDir)) {

Link to comment
Share on other sites

Print the $ImageDir variable and make sure that you are giving it the correct path. If the path exists, then go into Windows Explorer, right-click the folder you are trying to save to, go to the Security or Permissions page, and make sure the internet user account (IUSR_<server>) has access to write to the folder. That is for IIS, if you are using Apache I'm not sure what account Apache uses.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...