Uploading images with PHP and hitting the script m

2019-05-17 07:52发布

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?

6条回答
Melony?
2楼-- · 2019-05-17 08:01

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.

查看更多
虎瘦雄心在
3楼-- · 2019-05-17 08:05
$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

查看更多
混吃等死
4楼-- · 2019-05-17 08:06

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.

查看更多
干净又极端
5楼-- · 2019-05-17 08:17

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.

查看更多
ゆ 、 Hurt°
6楼-- · 2019-05-17 08:22

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.

查看更多
手持菜刀,她持情操
7楼-- · 2019-05-17 08:22

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.

查看更多
登录 后发表回答