Allowed memory size of bytes exhausted

Allowed memory size of bytes exhausted

I was getting Fatal Error: Allowed memory size of 67108864 bytes exhausted from one of my PHP script. I allowed Multiple Files upload and the image processing at line 82 was too RAM exhaustive, causing Allowed memory size of bytes exhausted error.
I thought image processing of large files (approx 1MB) only caused the problem, but single compressed image of small KB was also not processed properly.
PHP GD uncompress prior image manipulation and hence compression has no effect !

The GD Function causing this error was "imagecreatetruecolor()", the specified size was large enough to exhaust memory of the server. When I Googled for "Allowed memory size of bytes exhausted" there were pages suggesting to increase RAM to more than 1 GB and more, to me it would hardly solve the problem. If there are thousand of users and each uploading large images , any amount of RAM will never be enough !

Unless your website is specifically about photo editing, allowing billboard size in "imagecreatetruecolor()" makes no sense. Fixing the processed image height and width solved this problem.
<?php
//Set max allowed height and width of uploaded image as you wish
$maxallowedwidth = 700;
$maxallowedheight = 400;

$imgwidth = imagesx($srcimage);
$imgheight = imagesy($srcimage);

//To remove "Allowed memory size of 67108864 bytes exhausted problem", fix max height and width of image
if ($maxallowedwidth && ($imgwidth < $imgheight)) {$maxallowedwidth = ($maxallowedheight / $imgheight) * $imgwidth;}
else {$maxallowedheight = ($maxallowedwidth  / $imgwidth) * $imgheight;}

$newimg = imagecreatetruecolor($maxallowedwidth, $maxallowedheight);
//Do some image manipulation

//Clear memory
imagedestroy($srcimage);
imagedestroy($newimg);
?>
Other tips to avoid this error is :
* Avoid using Memory exhaustive functions in loop e.g. within foreach, while etc. in PHP
* Clear the memory immediately after image processing using PHP unset() and imagedestroy()
* Check with PHP memory_get_usage() function, amount of memory, allocated to your PHP script

For me the image manipulation created this problem but if your case is different, you can still focus on the line which is generating the error and modify your script using these tips to avoid "Allowed memory size of bytes exhausted" issue.