Jump to content

[solved] Php Resize & Upload Image


morrisjohnny
 Share

Recommended Posts

Okay i'm using this script to upload images and size them automatically. Problem is. is it is a small image i am upload it uploads fine, However uploading a large image and it fails to upload an error return "mysql gone away" is return. Also the script to resize the images are not working and has now got me wondering if this is why it's rejecting the large images.

//functionsfunction resize_image($opts){$src = isset($opts['source']) ? $opts['source'] : '';$dest = isset($opts['dest']) ? $opts['dest'] : '';$w = isset($opts['w']) ? intval($opts['w']) : 0;$h = isset($opts['h']) ? intval($opts['h']) : 0;if ($src == ''){return false;}if ($w == 0 && $h == 0){return false;}if ($dest == '')$dest = $src; // resize in place// open the image$ext = strtolower(array_pop(explode('.', $src)));switch ($ext){case 'jpg':case 'jpeg':$i = imagecreatefromjpeg($src);break;case 'gif':$i = imagecreatefromgif($src);break;case 'png':$i = imagecreatefrompng($src);break;default:return false;}$new_w = imagesx($i);$new_h = imagesy($i);if (($w != 0 && $new_w < $w && $h == 0) ||($w == 0 && $h != 0 && $new_h < $h) ||($w != 0 && $new_w < $w && $h != 0 && $new_h < $h)){// image is small enoughif ($dest != $src){copy($src, $dest);chmod($dest, 0644);}return true;}// determine new sizeif ($w != 0 && $new_w > $w){$new_h = ($w / $new_w) * $new_h;$new_w = $w;}if ($h != 0 && $new_h > $h){$new_w = ($h / $new_h) * $new_w;$new_h = $h;}// resize$new = imagecreatetruecolor($new_w, $new_h);imagecopyresampled($new, $i, 0, 0, 0, 0, $new_w, $new_h, imagesx($i), imagesy($i));imagedestroy($i);// save the imageswitch ($ext){case 'jpg':case 'jpeg':imagejpeg($new, $dest);break;case 'gif':imagegif($new, $dest);break;case 'png':imagepng($new, $dest);break;}chmod($dest, 0644);imagedestroy($new);return true;}//Start Final Functionfunction handle_file_upload($options){$input = !empty($options['input']) ? $options['input'] : trigger_error('handle_file_upload: No input name specified', E_USER_ERROR);$dest = !empty($options['dest_dir']) ? $options['dest_dir'] : trigger_error('handle_file_upload: No destination name specified', E_USER_ERROR);$dest_fname = !empty($options['dest_fname']) ? $options['dest_fname'] : '';$overwrite = !empty($options['overwrite']) ? $options['overwrite'] : false;$mode = !empty($options['mode']) ? $options['mode'] : false;$allowed_ext = isset($options['allowed_ext']) && is_array($options['allowed_ext']) ? $options['allowed_ext'] : false;if (!is_dir($dest))trigger_error('handle_file_upload: Destination directory does not exist', E_USER_ERROR);if (!isset($_FILES[$input]))trigger_error('handle_file_upload: The input file was not found', E_USER_ERROR);	if ($_FILES[$input]['error'] > 0)	{	switch ($_FILES[$input]['error'])	{	case 1:	case 2; return array('success' => false, 'error' => 'The uploaded file was too large.');	case 3: return array('success' => false, 'error' => 'The uploaded file was only partially received.');	case 4: return array('success' => false, 'error' => 'No file was uploaded.');	case 6: return array('success' => false, 'error' => 'Missing temporary folder.');	case 7: return array('success' => false, 'error' => 'Failed to write file to disk.');	case 8: return array('success' => false, 'error' => 'Invalid extension.');	}}if ($allowed_ext != false && !in_array(strtolower(array_pop(explode('.', $_FILES[$input]['name']))), $allowed_ext))return array('success' => false, 'error' => 'That file type was not allowed.');if ($dest_fname != '')$_FILES[$input]['name'] = $dest_fname;$_FILES[$input]['name'] = strtolower(basename($_FILES[$input]['name']));if (!$overwrite){$fname = $_FILES[$input]['name'];if (file_exists($dest . DIRECTORY_SEPARATOR . $fname)){$chunks = explode('.', $fname);$ext = array_pop($chunks);$fname = implode('.', $chunks);$nr = 1;while (file_exists($dest . DIRECTORY_SEPARATOR . $fname . '.' . $ext))$fname = $fname . '.' . $nr++;$_FILES[$input]['name'] = $fname . '.' . $ext;}}$target = $dest . DIRECTORY_SEPARATOR . $_FILES[$input]['name'];if (!move_uploaded_file($_FILES[$input]['tmp_name'], $target))return array('success' => false, 'error' => 'The uploaded file could not be moved.');if ($mode !== false)chmod($target, $mode);return array('success' => true, 'name' => $_FILES[$input]['name']);}//end functions

Edited by morrisjohnny
Link to comment
Share on other sites

Let's handle one thing at a time. Comment out the MySQL code and instead just print the query, and let's get it to upload, move the file, and resize. Moving the file and resizing doesn't have anything to do with MySQL, so get rid of the MySQL code and let's make sure the other part works first.

Link to comment
Share on other sites

Okay I've removed the MySQL code and removed the file resizing.SOME images can be uploaded however it depends on the file size. here's what i'm using to limit the file size<input type="hidden" name="MAX_FILE_SIZE" value="150000000000000000000000"> so surely that isn't going to be exceeded and the error return is "MySQL has gone away" which would implie the the server timed out or closed the connection?Here's a snippet of the new changes

		if(isset($_POST['name']))		{			if (isset($_POST['completed']))			{//images$file = handle_file_upload(array(			'input' => 'imagefile',			'dest_dir' => dirname(__FILE__),  // to upload to the current directory			'dest_fname' => 'latest.img', // optional			'overwrite' => true, // optional			'mode' => 0664, // optional			'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional		  ));		  if (!$file['success'])		  {			$errmsg = $file['error'];		  }		  else		  {			$instr = fopen($file['name'],"rb");			}$file2 = handle_file_upload(array(			'input' => 'imagefile2',			'dest_dir' => dirname(__FILE__),  // to upload to the current directory			'dest_fname' => 'latest2.img', // optional			'overwrite' => true, // optional			'mode' => 0664, // optional			'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional		  ));		  if (!$file2['success'])		  {			$errmsg = $file2['error'];		  }		  else		  {			$instr2 = fopen($file2['name'],"rb");			}   			}		   $image1=addslashes(fread($instr,filesize($file['name'])));			$image2=addslashes(fread($instr2,filesize($file2['name'])));			$name=mysql_real_escape_string($_POST['name']);			$price=mysql_real_escape_string($_POST['price']);			$type=mysql_real_escape_string($_POST['type']);			$description=mysql_real_escape_string($_POST['description']);			print(mysql_query("INSERT INTO products (Name, Price, Type, Description, img1, img2) VALUES ('$name','$price','$type','$description','$image1','$image2')"));/*			if(!mysql_query("INSERT INTO products (Name, Price, Type, Description, img1, img2) VALUES ('$name','$price','$type','$description','$image1','$image2')"))			{$result=mysql_error();}			else			{$result=stripslashes($_POST['name']).' Sucessfully Added';}*/		}

Link to comment
Share on other sites

There's also a size limit defined in php.ini, but the handle_file_upload function will detect any error with the file upload and return it. But the file upload literally has nothing to do with MySQL. Your MySQL error is not because of the file upload, the two have nothing to do with one another. You're still running the query and trying to print the result, just print the query out instead of running it. You're also not printing the error message from the file upload, it's being saved to the $errmsg variable but you're not doing anything with it. You're not handling the upload errors, so if there was an upload error you would have skipped opening the files and creating $instr and $instr2, so down when you go to create the query you're going to get fread errors when you try to read from a stream that doesn't exist.

Edited by justsomeguy
Link to comment
Share on other sites

Okay this might sound stupid. but how do i print out the query?as the page is password protected and the website will be getting used by a family member for their business the file size isn't really relavent however it was included incase i later decided to add this feature.Thanks for pointint out the $errmsg i totally overlooked that. i echoed it out and when mysql gone away is shown no $errmsg is reported. however i have provided a fix for this (off the current page.) i will fix the error for fread relating to $errmsg once the uploading aspect has been fix as this is a "rush copy" as this website has now been classified as important. and a first draft is required.

Link to comment
Share on other sites

Okay after following your suggestions the information is printed out and appears correct it shows "INSERT INTO products (Name, Price, Type, Description, img1, img2) VALUES ('','','2','','(a large amount of characters, which would happen to be the image in binary form correct?)"

Link to comment
Share on other sites

The files appear to be getting uploaded when printing the query out HOWEVER when trying to insert the image an error is returned saying mysql gone away. and the files are NOT being resized. (i tested this with a small file sized image but large scale file.

Link to comment
Share on other sites

Okay i tried to insert two images again from the same form it it showed the same information HOWEVER it cut off half way through and that wasn't changing anything from the same code as above (which i stated work preiously) i will type the full location of the fold (http://localhost/business/AJS Clothing/WIP/(then the code for the filename) that should work correct?will try and re-insert the image resizing size. it appears to me that the image is being read ( to enter the database and is then being resized. and not saved or re-opened is that correct or)?Thanks

Link to comment
Share on other sites

Don't use the HTTP path for the resize, use the filesystem path. e.g. c:\inetpub\wwwroot\... or whatever. Your first code had you resizing the image after reading it for the database, you need to resize it first so that when you read it it's already resized. Resizing the image isn't going to change the data that you already read.

Link to comment
Share on other sites

You can use the dirname function, dirname(__FILE__) returns the directory of the current script, for example. The resize function opens, resizes, and saves the file. All you need to do is call the resize function, then read the data from the file like you're already doing. You're just doing it in the wrong order, you're reading the data from the file on disk and then resizing the file on disk. You need to switch that.

Link to comment
Share on other sites

Okay so from this

file2 = handle_file_upload(array(			'input' => 'imagefile2',			'dest_dir' => dirname(__FILE__),  // to upload to the current directory			'dest_fname' => 'latest2.img', // optional			'overwrite' => true, // optional			'mode' => 0664, // optional			'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional		  ));		  if (!$file2['success'])		  {			$errmsg = $file2['error'];		  }		  else		  {			$instr2 = fopen($file2['name'],"rb");		$success = resize_image(array(		  'source' => $file2['name'], // image to resize		  'w' => 500, // max width		  'h' => 500 // max height		   )		   );}

TO this should work correct?

file2 = handle_file_upload(array(			'input' => 'imagefile2',			'dest_dir' => dirname(__FILE__),  // to upload to the current directory			'dest_fname' => 'latest2.img', // optional			'overwrite' => true, // optional			'mode' => 0664, // optional			'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional		  ));		  if (!$file2['success'])		  {			$errmsg = $file2['error'];		  }		  else		  {		$success = resize_image(array(		  'source' => $file2['name'], // image to resize		  'w' => 500, // max width		  'h' => 500 // max height		   )		   );			$instr2 = fopen($file2['name'],"rb");}

Correct or am i missing something total out here? i can't seem to understand the concept of image uploading.

Link to comment
Share on other sites

I changed the code like you suggest and still it says mysql has gone away. and i'm unable to see if thats succesfully resized the image.Surely after resizing the image then reading it will resize it before it's imported into the database correct? or will i need to resave it aswell?EDIT: okay i uploaded a file with a small file size but with larger dimensions and still the image hasn't been resized. :)the uploading of images seems to fail when the file is over a certain size, now the i want to automate the process to ensure the user doesn't have to change their qualitly of the pictures or mess around with their camra, hence why i'm trying to resize the pictures in order to take out some of the file size.

Edited by morrisjohnny
Link to comment
Share on other sites

and i'm unable to see if thats succesfully resized the image.
You should be able to double-click on the images to open them and check.
Surely after resizing the image then reading it will resize it before it's imported into the database correct? or will i need to resave it aswell?
You're going to insert whatever data into the database that you read. If you read the image before you resize it, then the data that you're going to put in the database is the original image. If you read the image after resizing it, then the data will be the resized image. Resizing the image saves over the original file.You're telling it to resize to 500x500 max, if the image is already smaller than that it's not going to resize it.
the uploading of images seems to fail when the file is over a certain size
If the upload fails then you're probably hitting one of the limits in php.ini. The handle_uploaded_file function will return that error if it happens though. Make sure to print out the error messages if handle_uploaded_file fails. I believe there are 2 options in php.ini that affect this, I think one is max_upload_size and one is max_request_size. I'm not positive about those names though, I haven't looked them up.
Link to comment
Share on other sites

Okay the image doesn't get reszied for some werid reason. after using this code

$file2 = handle_file_upload(array(			'input' => 'imagefile2',			'dest_dir' => dirname(__FILE__),  // to upload to the current directory			'dest_fname' => 'latest2.img', // optional			'overwrite' => true, // optional			'mode' => 0664, // optional			'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional		  ));		  if (!$file2['success'])		  {			$errmsg = $file2['error'];		  }		  else		  {			$instr2 = fopen($file2['name'],"rb");		$success = resize_image(array(		  'source' => $file2['name'], // image to resize		  'w' => 500, // max width		  'h' => 500 // max height		   )		   );}

You're telling it to resize to 500x500 max, if the image is already smaller than that it's not going to resize it.
sorry i ment to say the dimensions where bigger than 500 by 500 but still wasn't resized down. although the total file size was below this limit which seems to be failing.The images are being uploaded but not imported into the database, prehaps due to the resizing not taking place? if i open latest.img or latest2.img the newest pictures are their but not in the database.
Link to comment
Share on other sites

You are still opening the file before you resize it!This shouldn't be this difficult - you upload an image, and copy the file to wherever the destination is. Then you need to resize it. Then you need to open and read the data (can use file_get_contents for that instead of fopen+fread). If all of those things happen, in that order, the data you have for the database will be the resized uploaded image. You're still opening the file before you resize it:$instr2 = fopen($file2['name'],"rb");$success = resize_image(array(...That might even cause the resize to fail since the file is already open.

Edited by justsomeguy
Link to comment
Share on other sites

		  {		$success = resize_image(array(		  'source' => $file2['name'], // image to resize		  'w' => 500, // max width		  'h' => 500 // max height		   )		   );			$instr2 = fopen($file2['name'],"rb");}

Yeah, that will resize the image and then read it. What don't you understand about it?
Okay, well since i have reszed the image their how to i Re-Save the image without uploading it again? since it's being opened again after i resized it. surel'y it is just a simple one line to save the new resized image overwriting the existing file.?then that would be the end of my problem wouldn't it?
Link to comment
Share on other sites

If you only give it a source it will save over the original file, correct. You can check the return value of the resize_image function to see if it worked, if it's not working you might want to add some debugging echo statements to resize_image to see what it's doing. Also, make sure errors are enabled:error_reporting(E_ALL);ini_set('html_errors', 1);ini_set('log_errors', 0);ini_set('display_errors', 1);

Link to comment
Share on other sites

Errors are enabled. no error is given apart from mysql has gone awayi have tried to display $errmsg nothing is displayed and tried to show $file2['error'] and $file['error']; again nothing is shown. How would i go about debugging resize_image? it appears to be the saving of the image that is the problem then correct?

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
 Share

×
×
  • Create New...