Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading images with PHP and hitting the script memory limit

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?

like image 386
chustar Avatar asked Mar 16 '26 15:03

chustar


2 Answers

The actual problem is not with the initial file size but with the dimensions of the image itself (heightwidthcolorDepth), 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.

like image 178
Kristoffer Sall-Storgaard Avatar answered Mar 18 '26 07:03

Kristoffer Sall-Storgaard


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.

like image 34
Bill Karwin Avatar answered Mar 18 '26 05:03

Bill Karwin