[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 350
  • Last Modified:

When using GD library, resize/upload doesnt work in some cases

Hello,

I am having a strange problem when i try to resize and upload images. The upload form is working fine except when i use some types of larger images. heres the problem. Lets say i try to upload an image which is 135 KB and is 1600w x 1200h. Uploads great and creates the thumb too. Now when i try to upload another image, same dimensions but this time size is 665 KB, it says copy was unsuccessful. I increased the mAX UPLOAD SIZE to really high, but doesnt make a difference. (my php.ini max is 2MB too).

The only difference between these 2 images is in the one which worked - the first one, i actually almost painted the entire image with one color. However the second one, its an actual multicolored photo. I also tried with several other photos (the second kind variety) but none of them seemed to work. I am attaching the code here... there's a bit to it. Its well commented though.

ALso the error says this: Copy unsuccessfull!


//define a maxim size for the uploaded images
define ("MAX_SIZE","10000000");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","150");
define ("HEIGHT","100");

// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
//get image extension.
$ext=getExtension($img_name);
//creates the new image using the appropriate function from gd library
if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);

if(!strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);

//gets the dimmensions of the image
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);

// next we will calculate the new dimmensions for the thumbnail image
// the next steps will be taken:
// 1. calculate the ratio by dividing the old dimmensions with the new ones
// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
// and the height will be calculated so the image ratio will not change
// 3. otherwise we will use the height ratio for the image
// as a result, only one of the dimmensions will be from the fixed ones
$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;
}

// we create a new image with the new dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

// resize the big image to the new created one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

// output the created image to the file. Now we will have the thumbnail into the file named by $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);

//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}

// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

// This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
$errors=0;
// checks if the form has been submitted
if(isset($_POST['submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
// if it is not empty
if ($image)
{
// get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);

// get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
// if it is not a known extension, we will suppose it is an error, print an error message
//and will not upload the file, otherwise we continue
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png"))
{
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
// get the size of the image in bytes
// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($sizekb > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (uploadsfolder)
$newname="../customers/uploads/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
//we verify if the image has been uploaded, and print error instead
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}
else
{
// the new thumbnail image will be placed in uploads/thumbs/ folder
$thumb_name='../customers/uploads/thumbs/thumb_'.$image_name;
// call the function that will create the thumbnail. The function will get as parameters
//the image name, the thumbnail name and the width and height desired for the thumbnail
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
}} }}

//If no errors registred, print the success message and show the thumbnail image created
if(isset($_POST['submit']) && !$errors)
{
echo "<h1>Thumbnail created Successfully!</h1>";
echo '<img src="'.$thumb_name.'">';
}
0
stevegingell
Asked:
stevegingell
  • 17
  • 15
  • 3
  • +1
1 Solution
 
aot2002Commented:
Hi stevegingell,

are you sure that path is correct
do you have write permissions and does it exist?
../customers/uploads/

Cheers!
0
 
stevegingellAuthor Commented:
Hi aot2002. Yes the path has to be correct as my other images like i mentioned before are uploading just fine. Its only when i try the second kind that it doesnt work. Thanks.
0
 
ClickCentricCommented:
What are the filenames of the 2 images?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
stevegingellAuthor Commented:
Hi ClickCentric,
well the first one - the one which works fine is called image_gray.jpg. I later renamed it to ImageGray.jpg. It worked in both cases.

The second one is called BillPheat.jpg, so as you can see there's no difference in filenames.
0
 
ClickCentricCommented:
Is the full file uploading to the server?  ie is the file on the server the same size as the one you're uploading?  My first guess is that you're running out of temp space where the images are stored.
0
 
stevegingellAuthor Commented:
I looked at my ini file and i dont see any place where there is a restriction on either maximum file upload size or the size of the temp folder. In any case, if it was a size of folder issue and i had reched the limit, then i wouldnt be able to repeatedly upload my first type of image successfully (ImageGray.jpg). Here is upload section of ini file:

;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = "${path}\tmp\"

; Maximum allowed size for uploaded files.
upload_max_filesize = 2M
0
 
ClickCentricCommented:
Well, if you're running out of temp space, it could repeatedly upload the first image successfully as long as the first image is smaller.  I'm guessing it was just a flub when you said you don't see a restriction on the maximum file upload size as the last line above is where it's set.  But did you check to see if the temp uploaded file is the same size as the file you're trying to upload?  Even if the copy fails, the temp file should remain.  
0
 
ClickCentricCommented:
And you're copying the file, but not deleting the temp file.  Are you using a garbage collection routine somewhere to delete the old temp files?  
0
 
stevegingellAuthor Commented:
You are right, I had not meant there's no restriction on upload size. The second type of file which fails every time is around 665 KB, which is much less than the 2 MB limit. The problem is if I can upload a 135 KB file successfully then why not a 665 K ?
0
 
stevegingellAuthor Commented:
yeah i am destroying the temp images using this:

//destroys source and destination images.
imagedestroy($dst_img);
imagedestroy($src_img);
}
0
 
ClickCentricCommented:
No, that destroys the temp images you're creating in memory to resize...I'm talking about the temp file that the image is stored in..the actual file created on the server to store it.  

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = "${path}\tmp\"

The above tells php where to store these files when they're uploaded.  $_FILES['image']['tmp_name'] should return a filename relative to that path.  That's where the uploaded information gets stored until it's processed.  But if you're not deleting them, then each attempt is leaving the file there if no garbage collection is being performed.
0
 
stevegingellAuthor Commented:
I follow you now. What is the best way to do the garbage collection. Do you think you can throw in a piece of code to show it. Thanks.
0
 
ClickCentricCommented:
Well, all you need to do is unlink the file

unlink($_FILES['image']['tmp_name']);

Have you determined yet if the full file is uploading?
0
 
stevegingellAuthor Commented:
oh thats it huh...ok i am going to try that. I dont have access to my office computer from home, so will have to try it tomorrow morn at 8. Am really hoping it fixes the problem, already have spent hours trying to figure it out. Will let you know if it works. Good night!
0
 
Richard QuadlingSenior Software DeverloperCommented:
$copied = False;
if (is_uploaded($_FILES['image']['tmp_name']))
 {
 $copied = move_uploaded_file($_FILES['image']['tmp_name'], $newname);
 }
...


You should not access the uploaded files directly.

http://www.php.net/manual/en/function.move-uploaded-file.php,  http://www.php.net/manual/en/function.is-uploaded-file.php and http://www.php.net/manual/en/features.file-upload.php

would be good reading for this issue.
0
 
ClickCentricCommented:
RQuadling's recommendation is right, you shouldn't access uploaded files directly as strange things can happen.  But I wasn't suggesting that as a fix for the problem, was just pointing it out as I couldn't see from the code you posted how you were handling it.  You still need to check whether the uploaded temp file is the same size as the file you're trying to upload.  And you need to see if there are size restrictions on that directory and what they are if there are.  
0
 
stevegingellAuthor Commented:
Hi ClickCentric,
I checked to see if the directory has any size restrictions but i didnt see any. What did you mean by "You still need to check whether the uploaded temp file is the same size as the file you're trying to upload". When i check my tmp folder immeditaely after i tried to upload either first type or second type of file, there is a file inside the tmp folder which is updated, but it looks like a session file, goes something like this "sess_381cb81df8a7134c994b6dd100c062d4". I dont see any jpg's at all. Doesnt even look like anything is getting stored in tmp.

But even if its not getting store, how come the first type is uploaded fine whereas the second odesnt. I am totally confused by now.

I also tried Rquadling's recommendation but did not make a difference: hers where i changed it:

.................
//the new name will be containing the full path where will be stored (images folder)
$newname="../customers/uploads/".$image_name;
$copied = False;
if (is_uploaded_file($_FILES['image']['tmp_name']))
 {
 $copied = move_uploaded_file($_FILES['image']['tmp_name'], $newname);
 }
//we verify if the image has been uploaded, and print error instead
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';.........
0
 
ClickCentricCommented:
Ok, nevermind...forgot that php automatically deletes temporary uploaded files when script execution ends.  In the above, right before the $copied = False; put:

echo "Filesize: " . $_FILES['image']['size'] . "<br />";


This should output the size of the temp uploaded file before trying to move it.  
0
 
stevegingellAuthor Commented:
Ok it says Filesize: 0
0
 
ClickCentricCommented:
Ok, so the file isn't getting uploaded..  Have you tested that with both files?  The smaller one should be showing an accurate size.
0
 
stevegingellAuthor Commented:
Yes thats absolutely right. The smaller one works. Ok i just tried uploading a bunch of files with different sizes. it seems like the cut-off is around 510 KB. everything below that is uploading fine, but as soon as i cross that mark doesnt work.
0
 
ClickCentricCommented:
Check your php.ini for the lines 'memory_limit' and 'post_max_size'.  What are they set to?
0
 
stevegingellAuthor Commented:
Just checked both. Both were set at 8 MB. Increaded em both to 800 MB. Still dont work.
0
 
stevegingellAuthor Commented:
Hey ClickCentric, I've looked all over the file but still dont see a ~500 KB limit anywhere. Its crazy, because it is hitting the cutoff somehwre, its just not obvious when you look at it.

Any luck on your side. Do you think i should repost the question to get some more ideas. Thanks
0
 
ClickCentricCommented:
Can you post the url to the page?  I'm starting to wonder if the problem may not be on your end.  
0
 
stevegingellAuthor Commented:
i cannot, its running on my local, and i wont have access to the live server until later. If you want my local url its... http://127.0.0.1/classified/customers/add_photos1.php?id=89
0
 
ClickCentricCommented:
Well, 127.0.0.1 is the local loopback address for connecting to your own machine.  Is there no external access to it?  And if you're uploading it locally, that could be part of the problem.  May be flooding the connection.  This may work fine on an external server.
0
 
stevegingellAuthor Commented:
Unfortunately I need to absolutely make sure that it works fine in my local before i can make it live. I am reposting the Q, this time with specific size prolem. Get some more ideas flowing.
0
 
ClickCentricCommented:
At the least, try using your computer's actual IP address instead of the loopback address.  Such a thing can cause anomalies that normally wouldn't be there.
0
 
stevegingellAuthor Commented:
How would i do that. Just get the ip address out of ipconfig and stick it the url in place of 127.0.0.1?
0
 
stevegingellAuthor Commented:
Hey ClickCentric, ok it finally works now. I am glad i reposted and got some other ideas. All i had to do was put this in my html side:

<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />

That's it! I will still give you the 500 pts as you helped me get very close. Thanks.
0
 
ClickCentricCommented:
Oh geez...I actually knew that and I completely missed it.  You can ask for a refund on this question, though.  I appreciate the offer, but I didn't solve the problem, so there's no reason to give me the points.  
0
 
stevegingellAuthor Commented:
But I insist you have it. Had you not gotten me this close i would have spent another day figuring it out. Time is points :)
0
 
Richard QuadlingSenior Software DeverloperCommented:
Be aware that the MAX_FILE_SIZE is not enforced on all browsers. You may still get some idiot uploading that really nice 24mb 180,000 pixel square image of the Orion Nebula from NASA (I have a nice 5" square poster - its great!)
0
 
ClickCentricCommented:
Well, true...but the upload_max_filesize and post_max_size should prevent that on the server side.  
0
 
Richard QuadlingSenior Software DeverloperCommented:
Yes.

The server should ALWAYS be the place you do the checking. Supply things to the client to help, but never rely on them.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 17
  • 15
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now