• Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
Sign in to follow this  
Followers 0
morrisjohnny

[solved] Php Resize & Upload Image

30 posts in this topic

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

Share this post


Link to post
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.

Share this post


Link to post
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';}*/		}

Share this post


Link to post
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

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

You have this line:print(mysql_query("INSERT INTO products (Name, Price, Type, Description, img1, img2) VALUES ('$name','$price','$type','$description','$image1','$image2')"));Remove the "mysql_query" part, and just print the actual query.

Share this post


Link to post
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?)"

Share this post


Link to post
Share on other sites

So are the files getting uploaded and resized?

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

The image resize code went away, where did that go? Make sure to give it the full path to the file, not just the filename. Since you're printing out the query, copy and paste that into phpMyAdmin and see if it runs there.

Share this post


Link to post
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

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

How would i be able to determind the system path on a internet server? and i would have to open the file to resize it, save it then re-open it again correct? How would i go about doing this?

Share this post


Link to post
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.

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Yeah, that will resize the image and then read it. What don't you understand about it?

Share this post


Link to post
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

Share this post


Link to post
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.

Share this post


Link to post
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.

Share this post


Link to post
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

Share this post


Link to post
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?

Share this post


Link to post
Share on other sites

The resize_image function saves over the original file unless you give it a new destination filename to save the resized image as.

Share this post


Link to post
Share on other sites

I never gave it another name, so it should have saved over the orginal image. Correct? as it never it must mean theirs an error with the resizing of the file or it's simply not saving right?

Share this post


Link to post
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);

Share this post


Link to post
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?

Share this post


Link to post
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
Sign in to follow this  
Followers 0