Uploading images with PHP and hitting the script memory limit

我是研究僧i 提交于 2019-12-07 18:25:28

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


$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




回答6:


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.



来源:https://stackoverflow.com/questions/3562809/uploading-images-with-php-and-hitting-the-script-memory-limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!