views:

58

answers:

6

I am trying to upload a JPG image using a PHP script, but the image is keeps causing my script to time out and die giving this error:

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 
2136 bytes) in image.php on line 38

How can I prevent the upload from taking place if the image is too big, or have this error fail gracefully?

+2  A: 

http://php.net/manual/en/features.file-upload.common-pitfalls.php says:

If a memory limit is enabled, a larger memory_limit may be needed. Make sure you set memory_limit large enough.

Bill Karwin
A: 
$size=filesize($_FILES['image']['tmp_name']);

will give you the size of the file in the global $_FILES array. After this, just compare $size to the maximum size you want.

Check out thie filesize() api: http://php.net/manual/en/function.filesize.php

codersarepeople
+1  A: 

You can limit image size or any other file upload size on couple of ways,

via php.ini, upload_max_filesize = 10M

via invisible tag such as this(10k): <input type="hidden" name="MAX_FILE_SIZE" value="10000" />

I Would not recommend increase memory limit if you don't know what kind of implications it can have on your server configuration.

aromawebdesign.com
+2  A: 

The actual problem is not with the initial file size but with the dimensions of the image itself (height*width*colorDepth), since you don't have access to this information before the file has been uploaded for security reasons, you should probably use an uploader written in Flash, Java or Silverlight since they DO have access to this information beforehand.

After the upload you can check if the image will exceed your memory limit by calculating the dimensions of the (uncompressed) image by using getimagesize and using the returned width, height and bit depth.

Best of luck.

Kristoffer S Hansen
+1 exactly what I was going to write. Additionally, check out [this question from yesterday](http://stackoverflow.com/questions/3554397/estimate-required-memory-for-libgd-operation)
Pekka
+1  A: 

Just set the memory limit higher for that particular script only by using ini_set.

At the beginning of your image processing script:

ini_set('memory_limit', '64M');

This error is generally caused not by image file size, but rather image resolution. So you can run some check for the size of the image. Run some tests to see what's acceptable under your current memory limit, and if the resolution is higher then kill the process and return an error to the user.

Calvin L
A: 

Is this happening with all upload attempts regardless of file size? I have only experienced this sort of problem when there has been a scripting error - usually a loop that is out of control.

Leo