Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP allowed memory usage exhausted while I see no sign of it

Tags:

php

I have this simple PHP script that contains only the following few lines

$mem = memory_get_usage()/1024;
$mem = $mem/1024;
echo "mem: ".$mem ."Mb<br>";
$max =  ini_get('memory_limit');
echo "max is $max<br>";

$filename = 'upload/orig/CID_553.jpg';              
$filesize = (filesize($filename) / 1024);
echo "filesize is $filesize Kb<br>";        
$img_pointer = imagecreatefromjpeg($filename);

When running it, I get this output

mem: 0.30711364746094Mb
max is 64M
filesize is 952.2666015625 Kb
Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 13056 bytes) in C:\temp_checkmem.php on line 13 

How is it possible that loading a file of 952Kb will trap PHP (imagecreatefrompeg) into going over the allowed 64Mb of memory ? Any ideas?

like image 245
user410932 Avatar asked Jan 14 '23 01:01

user410932


1 Answers

Just because the JPG file is only 952kbytes doesn't mean it can't occupy a VERY large amount of memory, e.g.a simple test with a 2048x2048 pure white image produces a 59kbyte .jpg file.

That file will decompress to a 2048x2048x3 = 12.6 megabyte raw bitmap in GD.

You can get a rough estimate of how much memory WOULD be required by GD to load/decompress the image with:

$stats = getimagesize($filename);
$memory_estimate = $stats[0] * $stats[1] * 3; // height * width * 3 bytes per pixel
echo "{$stats[0]}x{$stats[1]} -> {$memory_estimate} bytes";
like image 173
Marc B Avatar answered Jan 15 '23 14:01

Marc B