PHP – Possible reasons of “Allowed memory size exhausted” error

|
| By Webner

Most of the times when we get memory exhausted error, we normally think that the memory allocated for php program execution in php.ini file is not sufficient and raise this limit to try to fix the error.

However, code inefficiency could be the reason behind the error. Some examples of code inefficiency are these :

Infinite loops can certainly exhaust the memory available. For example check this code :

<?php
for ($i=0; $i < $max;) { if ($x > $y)
{	
	$i++;
}
}
?>

1. As you can see $i is incremented inside if condition. That means if the condition is not true, $i will not be incremented and loop will continue forever (since loop is using $i).

2. When resources such as files, sessions are not closed/unset properly. In that case, resources continue to hold memory and can result in Memory Exhausted Errors.

3. If we execute database queries that result in enormous amount of data retrieval. Queries with large data sets can result in system going out of memory. Make sure your SELECT queries contain only the columns your program needs and you have appropriate WHERE clause in place.

Leave a Reply

Your email address will not be published. Required fields are marked *