Hello all,
I am trying to code for user's profile pic uploading and resizing the image.
I am using the following code and I dont know where I am going wrong!

<?php

//This is the directory where images will be saved
$target1 = "images/";
$target = $target1 . basename( $_FILES['photo']['name']);

//This gets all the other information from the form
$name=$_POST['name'];
$pic=($_FILES['photo']['name']);

// Connects to your Database
database connections

//Writes the information to the database
mysql_query("INSERT INTO `example` VALUES ('$name', '$pic')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
echo $_FILES['photo']['tmp'];
echo "Sorry, there was a problem uploading your file.";
}

$data = mysql_query("SELECT * FROM example") 
or die(mysql_error());  

while($info = mysql_fetch_array( $data ))
{

//Outputs the image and other data
echo "<b>Name:</b> ".$info['name'] . "<br> ";

echo "<img src=http://www.websitename.com/images/".$info['photo'] ."> <br>";


}
?>

Whats happening here is name and image name are getting stored in the database but nothing is stored in the images folder in the server. I am not getting the image displayed .
Can anyone suggest whats the exact method if the below code is wrong somewhere. Also any suggestions about how to resize the image uploaded.

Thank you in advance.

hello Kavitha,

This is my code which runs well. In fact I got it from this forum itself.

<?php
include("db_connect.php");

//Change this to the name of the page
$thispage = 'up.php';

//Set the allowed file types
$types = array("gif","jpeg","jpg","png");

//Set max size of image (in MB)
$maxSize = '40';

//Set upload directory
$uploadDir = 'upload';

//This function get the extension of the image
function getExtension($str) {
	$i = strrpos($str,".");
	if (!$i) {
		return "";
	}
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	return $ext;
}


if (isset($_POST['submit'])) {
	if (empty($_FILES['image']['name'])) {
		$result = 'Please choose an image';
	}
	else {
		$imageName = $_FILES['image']['name'];
		$exten = getExtension($imageName);
		if (!in_array($exten,$types)) {
			$result = 'Unknown extension, please choose a different image';
		}
		else {
			$tmpFile = $_FILES['image']['tmp_name'];
			$size = filesize($tmpFile);
			if ($size > ($maxSize * 1024)) {
				$result = 'Image exceeds size limit, choose a smaller image';
			}
			else {
       				$newName = $uploadDir . '/' . $imageName ;
					//. '.' . $exten;
				if (!copy($tmpFile,$newName)) {
					$result = 'Unable to upload image, try again';
				}
				else {
              					$sql   = "INSERT INTO `symbol` (symbol) VALUES ('<img src=" . $newName . " width=200>')";
              					$query = mysql_query($sql) or die('Error: ' . mysql_error());
					$result = 'Image Uploaded Successfully';
				}
			}
		}
	}
}
$html =<<<HTML
<form action="$thispage" method="post" enctype="multipart/form-data">
<table border="0" cellspacing="0" cellpadding="5">
	<tr>
		<td align="right">Image:</td>
		<td align="left"><input type="file" name="image" /></td>
	</tr>
	<tr>
		<td align="right">Key:</td>
		<td align="left"><input type="text" name="key" /></td>
	</tr>
	<tr>
		<td colspan="2" align="center"><input type="submit" name="submit" value="Upload" /></td>
	</tr>
	<tr>
         		<td colspan="2" align="center">$result</td>
	</tr>
</table>
</form>
HTML;

echo $html;

?>

The images are semt to the folder 'upload' an the filepath is sent to the database and as for retrieving and displaying the images:

<?php

include("db_connect.php"); 

error_reporting(E_ALL);

 // get the image from the db
  
      $sql = "SELECT symbol FROM symbol WHERE image_id=0";
  
       
  
      // the result of the query
  
    $result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
  
       
  
      // set the header for the image
  
     // header("Content-type: image/jpeg");
  	echo "<table >";
	echo "<tr><td align=center>";
    echo mysql_result($result, 0);
	echo "</td></tr></table>";
  
       
        // close the db link
  
       mysql_close();

This code works but the problem is that I am not being able to resize the images. When displayed, it is being displayed on the whole page. If you get to know how to do this let me know.

thanks for posting my code so i didn't have to write it again. :)

commented: :D +5

Hi,

Since it's ur code, can u please tell us how to resize the images retrieved from the database.

i resize them before i add them to do the database.

here is some code i have used on my last few projects (includes my upload code above):

<?php
include("db_connect.php");

//Change this to the name of the page
$thispage = 'up.php';

//Set the allowed file types
//NOTE ONLY JPEG and PNG file allowed because php doesn't have much image support for GIF
$types = array("jpeg","jpg","png");

//Set max size of image (in MB)
$maxSize = '40';

//Set maximum width and height of resized images (images will not be distorted)
define('WIDTH',150);
define('HEIGHT',150);

//Set temp directory where upload images will be stored before resizing
$tempDir = 'temp';

//Set upload directory where resized images will be stored
$uploadDir = 'upload';

//This function get the extension of the image
function getExtension($str) {
	$i = strrpos($str,".");
	if (!$i) {
		return "";
	}
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	return $ext;
}

//This function resizes the image
function make_thumb($img_name,$filename,$new_w,$new_h) {
	$ext = $this->getExtension($img_name);
	if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) {
		$src_img=imagecreatefromjpeg($img_name);
	}
	if(!strcmp("png",$ext)) {
		$src_img=imagecreatefrompng($img_name);
	}
	$old_x=imageSX($src_img);
	$old_y=imageSY($src_img);
	$ratio1=$old_x/$new_w;
	$ratio2=$old_y/$new_h;
	if($ratio1>$ratio2) {
		$thumb_w=$new_w;
		$thumb_h=$old_y/$ratio1;
	}
	else {
		$thumb_h=$new_h;
		$thumb_w=$old_x/$ratio2;
	}
	$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
	if(!strcmp("png",$ext)) {
		imagepng($dst_img,$filename);
	}
	else {
		imagejpeg($dst_img,$filename);
	}
	imagedestroy($dst_img);
	imagedestroy($src_img);
}

if (isset($_POST['submit'])) {
	if (empty($_FILES['image']['name'])) {
		$result = 'Please choose an image';
	}
	else {
		$imageName = $_FILES['image']['name'];
		$exten = getExtension($imageName);
		if (!in_array($exten,$types)) {
			$result = 'Unknown extension, please choose a different image';
		}
		else {
			$tmpFile = $_FILES['image']['tmp_name'];
			$size = filesize($tmpFile);
			if ($size > ($maxSize * 1024)) {
				$result = 'Image exceeds size limit, choose a smaller image';
			}
			else {
				$time = time();
				$newName = $tempDir . '/' . $time . '.' . $exten;
				if (!copy($tmpFile,$newName)) {
					$result = 'Unable to upload image, try again';
				}
				else {
					$finalName = $uploadDir . '/' . $time . '.' . $exten;
					$make = make_thumb($newName,$finalName,WIDTH,HEIGHT);
					$sql   = "INSERT INTO `symbol` (symbol) VALUES ('<img src=" . $finalName . " width=200>')";
					$query = mysql_query($sql) or die('Error: ' . mysql_error());
					$result = 'Image Uploaded Successfully';
				}
			}
		}
	}
}
$html =<<<HTML
<form action="$thispage" method="post" enctype="multipart/form-data">
<table border="0" cellspacing="0" cellpadding="5">
	<tr>
		<td align="right">Image:</td>
		<td align="left"><input type="file" name="image" /></td>
	</tr>
	<tr>
		<td align="right">Key:</td>
		<td align="left"><input type="text" name="key" /></td>
	</tr>
	<tr>
		<td colspan="2" align="center"><input type="submit" name="submit" value="Upload" /></td>
	</tr>
	<tr>
		<td colspan="2" align="center">$result</td>
	</tr>
</table>
</form>
HTML;

echo $html;

?>

Thankyou for the code Chitra and KKeith but unfortunately it is not working to me. Can someone please help me out with my code.

whats not working, are there any errors. did you change the variables in the script, what did you do to the script, did you make any other changes, ect.

by saying not working, it really doesn't help us find a solution.

Hello kkeith thankyou very much fr responding to my query.

I get nothing but empty page when I run this code.. seems like I need to change many variable names and am really confused where and which to change in the first case.

$sql   = "INSERT INTO `symbol` (symbol)  VALUES ('<img src=" . $finalName . " width=200>')";

* => Does 'symbol' here needs to be replaced by my table name ?
and can you please tell me where else should I make changes other than giving database connections.

Thankyou in advance,

you need to change the sql to suit your database. what does your table look like.

thank you fr responding.

my sql table has only two attributes,

name and pic

Can you please indicate where should I make specific changes!

then use:

$sql = "INSERT INTO `tablename` (`name`,`pic`) VALUES ('" . $name . "','" . $finalName . "')";

This time in the table the data is getting placed as following

name photo
NULL 56910032.jpg
NULL 56910032.jpg
NULL 56910032.jpg
NULL 56910032.jpg
NULL 56910032.jpg
NULL 56366477.jpg

but nothing is being uploaded into the 'upload' folder in the directory and hence I think the image is also not getting displayed on the page...

post your changed code

I have used the snippet over 10 times without any problems.

<?php
include("db_connect.php");
mysql_connect ("server", "adminlogin", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db (imagesdb);


//Change this to the name of the page
$thispage = 'up.php';

//Set the allowed file types
//NOTE ONLY JPEG and PNG file allowed because php doesn't have much image support for GIF
$types = array("jpeg","jpg","png");

//Set max size of image (in MB)
$maxSize = '40';

//Set maximum width and height of resized images (images will not be distorted)
define('WIDTH',150);
define('HEIGHT',150);

//Set temp directory where upload images will be stored before resizing
$tempDir = 'temp';

//Set upload directory where resized images will be stored
$uploadDir = 'upload';

//This function get the extension of the image
function getExtension($str) {
	$i = strrpos($str,".");
	if (!$i) {
		return "";
	}
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	return $ext;
}

//This function resizes the image
function make_thumb($img_name,$filename,$new_w,$new_h) {
	$ext = $this->getExtension($img_name);
	if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) {
		$src_img=imagecreatefromjpeg($img_name);
	}
	if(!strcmp("png",$ext)) {
		$src_img=imagecreatefrompng($img_name);
	}
	$old_x=imageSX($src_img);
	$old_y=imageSY($src_img);
	$ratio1=$old_x/$new_w;
	$ratio2=$old_y/$new_h;
	if($ratio1>$ratio2) {
		$thumb_w=$new_w;
		$thumb_h=$old_y/$ratio1;
	}
	else {
		$thumb_h=$new_h;
		$thumb_w=$old_x/$ratio2;
	}
	$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
	if(!strcmp("png",$ext)) {
		imagepng($dst_img,$filename);
	}
	else {
		imagejpeg($dst_img,$filename);
	}
	imagedestroy($dst_img);
	imagedestroy($src_img);
}

if (isset($_POST['submit'])) {
	if (empty($_FILES['image']['name'])) {
		$result = 'Please choose an image';
	}
	else {
		$imageName = $_FILES['image']['name'];
		$exten = getExtension($imageName);
		if (!in_array($exten,$types)) {
			$result = 'Unknown extension, please choose a different image';
		}
		else {
			$tmpFile = $_FILES['image']['tmp_name'];
			$size = filesize($tmpFile);
			if ($size > ($maxSize * 1024)) {
				$result = 'Image exceeds size limit, choose a smaller image';
			}
			else {
				$time = time();
				$newName = $tempDir . '/' . $time . '.' . $exten;
				if (!copy($tmpFile,$newName)) {
					$result = 'Unable to upload image';
				}
				else {
					$finalName = $uploadDir . '/' . $time . '.' . $exten;
					$make = make_thumb($newName,$finalName,WIDTH,HEIGHT);
					$sql   = "INSERT INTO `symbol` (symbol) VALUES ('<img src=" . $finalName . " width=200>')" or die('Error: ' . mysql_error());
					$query = mysql_query($sql) or die('Error: ' . mysql_error());
					$result = 'Image Uploaded Successfully';
				}
			}
		}
	}
}
$html =<<<HTML
<form action="$thispage" method="post" enctype="multipart/form-data">
<table border="0" cellspacing="0" cellpadding="5">
	<tr>
		<td align="right">Image:</td>
		<td align="left"><input type="file" name="image" /></td>
	</tr>
	<tr>
		<td align="right">Key:</td>
		<td align="left"><input type="text" name="key" /></td>
	</tr>
	<tr>
		<td colspan="2" align="center"><input type="submit" name="submit" value="Upload" /></td>
	</tr>
	<tr>
		<td colspan="2" align="center">$result</td>
	</tr>
</table>
</form>
HTML;

echo $html;




?>

I created a new table 'symbol' accordingly .This time nothing is getting into databse also.
That is the entire code am using.

Everything is fine in the above posted code. The only line which gave me an error was this line. $ext = $this->getExtension($img_name); Remove $this and everything will work great !

commented: thankyou fr ur time +1

oh yeah, i forgot to remove that since it was a function in a class of mine. sorry.

commented: thankyou fr ur time +1
commented: Well written script :) +7

Thankyou fr your time nav33n and kkeith.
As I am in the middle of another important module I have no time to check back on this now. kindly bear with me. I shall soon try it again in a day or two.Hope the code works fine this time when I check back.
Thankyou.

Everything is fine in the above posted code. The only line which gave me an error was this line. $ext = $this->getExtension($img_name); Remove $this and everything will work great !

Did you mean to say remove only '$this' and keep the rest of the line same.

$ext function is in use soo.. I tried removing $this-> and keeping the rest of the line same but am getting error again.

//This function get the extension of the image
function getExtension($str) {
	$i = strrpos($str,".");
	if (!$i) {
		return "";
	}
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	return $ext;
}

//This function resizes the image
function make_thumb($img_name,$filename,$new_w,$new_h) {
	$ext = getExtension($img_name);
	if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) {
		$src_img=imagecreatefromjpeg($img_name);
	}
	if(!strcmp("png",$ext)) {
		$src_img=imagecreatefrompng($img_name);
	}
	$old_x=imageSX($src_img);
	$old_y=imageSY($src_img);
	$ratio1=$old_x/$new_w;
	$ratio2=$old_y/$new_h;
	if($ratio1>$ratio2) {
		$thumb_w=$new_w;
		$thumb_h=$old_y/$ratio1;
	}
	else {
		$thumb_h=$new_h;
		$thumb_w=$old_x/$ratio2;
	}
	$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
	if(!strcmp("png",$ext)) {
		imagepng($dst_img,$filename);
	}
	else {
		imagejpeg($dst_img,$filename);
	}
	imagedestroy($dst_img);
	imagedestroy($src_img);
}

Thanks in advance.

It simply displays Image cannot be uploaded message after I try to upload image.

When I try to upload without image resizing code, images are getting successfully uploaded into the folder, problem comes only when I try to include resizing code as mentioned in the above posts code.Hence I dont think there is some problem with the permissions to upload the images into the respective folder.

It simply displays Image cannot be uploaded message after I try to upload image.

Is that a custom error or a php error?

Its custom error message.

this following code has that error message which is displayed after trying to upload images

}
			else {
				$time = time();
				$newName = $tempDir . '/' . $time . '.' . $exten;
				if (!copy($tmpFile,$newName)) {
					$result = 'Unable to upload image, try again';
				}

This would be easier if you could see a real error. I'm pretty sure it has to do with that resizing function, possible the paths going in, I don't know.

If your configuration file is set to block errors from being displayed you could put the following two lines at the top of the script and see if that makes a difference.

ini_set("display_errors", "1");
error_reporting (E_ALL);

The code works fine for me :) See if you have created the folder and it has all the permissions !

hi nav33n
can you tell me what to remove from the code in detail plz.
well I created the folder 'upload' and it has all the permissions too.
When I didnt use this resize code it worked fine :(

This would be easier if you could see a real error. I'm pretty sure it has to do with that resizing function, possible the paths going in, I don't know.

If your configuration file is set to block errors from being displayed you could put the following two lines at the top of the script and see if that makes a difference.

ini_set("display_errors", "1");
error_reporting (E_ALL);

Thankyou for this two lines of code.. am now able to see whats actually going wrong..hope this helps

did you create the temp directory?

did you create the temp directory?

yes I had created.

The warning messages I have been getting are:

Notice: Undefined variable: src_img in /up.php on line 50

Warning: imagesx(): supplied argument is not a valid Image resource in /up.php on line 50

Notice: Undefined variable: src_img in /up.php on line 51

Warning: imagesy(): supplied argument is not a valid Image resource in /up.php on line 51

Warning: Division by zero in /up.php on line 60

Warning: imagecreatetruecolor(): Invalid image dimensions in /up.php on line 62

Notice: Undefined variable: src_img in /up.php on line 63

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /up.php on line 63

Notice: Undefined variable: ext in /up.php on line 64

Warning: imagejpeg(): supplied argument is not a valid Image resource in /up.php on line 68

Warning: imagedestroy(): supplied argument is not a valid Image resource in /up.php on line 70

Notice: Undefined variable: src_img in /up.php on line 71

Warning: imagedestroy(): supplied argument is not a valid Image resource in /up.php on line 71
Error: Duplicate entry '0' for key 1

<?php

ini_set("display_errors", "1");
error_reporting (E_ALL);


mysql_connect("xyz", "adminlogin", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db(dbname) or die (mysql_error());

//Change this to the name of the page
$thispage = 'up.php';

//Set the allowed file types
//NOTE ONLY JPEG and PNG file allowed because php doesn't have much image support for GIF
$types = array("jpeg","jpg","png");

//Set max size of image (in MB)
$maxSize = '40';

//Set maximum width and height of resized images (images will not be distorted)
define('WIDTH',150);
define('HEIGHT',150);

//Set temp directory where upload images will be stored before resizing
$tempDir = 'temp';

//Set upload directory where resized images will be stored
$uploadDir = 'upload';

//This function get the extension of the image
function getExtension($str) {
	$i = strrpos($str,".");
	if (!$i) {
		return "";
	}
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	return $ext;
}

//This function resizes the image
function make_thumb($img_name,$filename,$new_w,$new_h) {
	getExtension($img_name);
	if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) {
		$src_img=imagecreatefromjpeg($img_name);
	}
	if(!strcmp("png",$ext)) {
		$src_img=imagecreatefrompng($img_name);
	}
	$old_x=imageSX($src_img);
	$old_y=imageSY($src_img);
	$ratio1=$old_x/$new_w;
	$ratio2=$old_y/$new_h;
	if($ratio1>$ratio2) {
		$thumb_w=$new_w;
		$thumb_h=$old_y/$ratio1;
	}
	else {
		$thumb_h=$new_h;
		$thumb_w=$old_x/$ratio2;
	}
	$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
	if(!strcmp("png",$ext)) {
		imagepng($dst_img,$filename);
	}
	else {
		imagejpeg($dst_img,$filename);
	}
	imagedestroy($dst_img);
	imagedestroy($src_img);
}

if (isset($_POST['submit'])) {
	if (empty($_FILES['image']['name'])) {
		$result = 'Please choose an image';
	}
	else {
		$imageName = $_FILES['image']['name'];
		$exten = getExtension($imageName);
		if (!in_array($exten,$types)) {
			$result = 'Unknown extension, please choose a different image';
		}
		else {
			$tmpFile = $_FILES['image']['tmp_name'];
			$size = filesize($tmpFile);
			if ($size > ($maxSize * 1024)) {
				$result = 'Image exceeds size limit, choose a smaller image';
			}
			else {
				$time = time();
				$newName = $tempDir . '/' . $time . '.' . $exten;
				if (!copy($tmpFile,$newName)) {
					$result = 'Unable to upload image, try again';
				}
				else {
					$finalName = $uploadDir . '/' . $time . '.' . $exten;
					$make = make_thumb($newName,$finalName,WIDTH,HEIGHT);
					$sql   = "INSERT INTO `symbol` (symbol) VALUES ('<img src=" . $finalName . " width=200>')";
					$query = mysql_query($sql) or die('Error: ' . mysql_error());
					$result = 'Image Uploaded Successfully';
				}
			}
		}
	}
}
$html =<<<HTML
<form action="$thispage" method="post" enctype="multipart/form-data">
<table border="0" cellspacing="0" cellpadding="5">
	<tr>
		<td align="right">Image:</td>
		<td align="left"><input type="file" name="image" /></td>
	</tr>
	<tr>
		<td align="right">Key:</td>
		<td align="left"><input type="text" name="key" /></td>
	</tr>
	<tr>
		<td colspan="2" align="center"><input type="submit" name="submit" value="Upload" /></td>
	</tr>
	<tr>
		<td colspan="2" align="center">$result</td>
	</tr>
</table>
</form>
HTML;

echo $html;

?>

Images are moving into temp directory and after that nothing else is happening.

When I changed line 43 in the above code to

$ext = getExtension($img_name);

Now Images are moving into upload directory too and
am getting only these two messages now,

Notice: Use of undefined constant mydatabasename - assumed 'mydatabasename' in /up.php on line 8
Error: Duplicate entry '0' for key 1

Thank You ALL, Its working now :) except that resizing of the images are making them little blurred... shall takecare of it anyways.
Thankyou kkeith29,nav33n,robbob,chitra for helping me .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.