Is there a way to prevent the PHP GD image library from running out of memory? If too large an image is uploaded, GD tends to run out of memory, terminating the script. I\'d
To catch PHP's fatal errors, like "Out of memory" or "PHP Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate … bytes) in", see here : http://php.net/manual/en/function.set-error-handler.php#88401
After you create an image.
imagepng($image);
imagedestroy($image);
will remove the memory problem
Buy more memory! :-P
Seriously though, it is impossible to handle being out of memory because any action you take would require more memory.
Your best bet is to limit the size of image being uploaded based on the current memory settings.
Do some tests to check how much memory each gd
function need.
imagecreatetruecolor
seems to need width*height*5 bytes
.
imagepng
seems to need width*height*4 bytes
.
There is another way to do it, but it can be time consuming, as certain parts of the image editing process would be repeated a number of times, but you can set the memory limit to your estimated value, then try to process the image, if it fails catch the exception, increase the memory limit, then process the image again - repeating this until you succeed or reach a certain memory limit - at which point you'd throw an error message to the user explaining that their image is too big to be used.
Edit: To catch the out-of-memory error, you could use this solution: http://au2.php.net/set_error_handler#35622
Your best bet is to stop trying to figure out how much ram it will need, and just max it out at the outset - if you have 4 GB available, tell the image script to use between 2 and 4 GB or so, and when the script ends, have it go back to normal, that will cover off all potentially fatal situations. That's the only "Fail-safe" way I can think of anyway ...