PHP Memory Limit
I ran into this issue today, while dealing with operations on a 20MB JSON string in a PHP application I was building.
The server responded with 500 internal server error, and the message was:
Allowed memory size of 134217728 bytes exhausted
What in tarnation is this???
I found out that the php.ini
file has a memory_limit
config variable, and mine was set to 128MB
, which is 134217728 bytes
.
Somehow, my code was using more than the allowed 128MB, which was kinda expected because 20MB JSON string, duh.
Set memory limit in php.ini
I found you could increase this by setting the value in the php.ini
file, so I did this.
php --ini #shows you the location of the file
nano /usr/local/etc/php/7.1/php.ini
I changed the value of memory_limit
to 512MB, and it worked.
Set it at runtime
However, I later saw that you could set the value within your PHP code at runtime by:
ini_set('memory_limit', '512MB');
Also, that you could remove the limit by setting the value to -1
, which is dope because you’re not restricting the server anymore.
Eat your cake and have it
I decided to try removing the limit just before the heavy work starts, and replacing it after it ends.
$limit = ini_get('memory_limit'); // retrieve the set limit
ini_set('memory_limit', -1); // remove memory limit
// do heavy work
ini_set('memory_limit', $limit);
and there we go … works beautifully!