Skip to content
PHP Fatal error: Allowed memory size of ... bytes exhausted

PHP Fatal error: Allowed memory size of ... bytes exhausted

DodaTech 2 min read

The “Allowed memory size exhausted” fatal error means your PHP script tried to allocate more memory than the memory_limit directive allows. This stops the script immediately and often indicates a problem with how your code uses memory.

What It Means

PHP has a configurable memory cap per request, typically set to 128M or 256M. When a script exceeds this limit (e.g., loading a huge file into memory, infinite array growth, or a memory leak in a loop), PHP throws this fatal error. The error message tells you exactly how many bytes were exhausted and the limit.

Why It Happens

  • Processing large files — reading an entire multi-GB file into a string or array.
  • Infinite loop with array growth — a while loop that keeps adding to an array with no exit condition.
  • Recursive function with no base case — infinite recursion exhausts the stack and memory.
  • Object references preventing garbage collection — circular references that PHP cannot free.
  • memory_limit set too low — the default 128M may not be enough for modern frameworks like Laravel or Symfony in production.
  • Loading a massive dataset from the database — fetching thousands of rows without pagination.

How to Fix It

1. Increase memory_limit temporarily

// At the top of your script
ini_set('memory_limit', '512M');

Or permanently in php.ini:

memory_limit = 512M

2. Unset large variables after use

$hugeData = fetchHugeDataset();
processData($hugeData);
unset($hugeData); // ✅ Free memory immediately

// Continue with other operations...

3. Process data in chunks instead of loading everything

// ❌ Loads everything into memory
$rows = $db->query("SELECT * FROM logs")->fetchAll();

// ✅ Processes one row at a time
$stmt = $db->query("SELECT * FROM logs");
while ($row = $stmt->fetch()) {
    processRow($row);
}

4. Optimize loops and recursion

// ❌ Infinite growth
$array = [];
while (true) {
    $array[] = str_repeat('x', 1000000);
}

// ✅ Always have a termination condition
$array = [];
$limit = 100;
for ($i = 0; $i < $limit; $i++) {
    $array[] = str_repeat('x', 10000);
}

5. Check memory usage

echo memory_get_usage() / 1024 / 1024 . ' MB';   // Current usage
echo memory_get_peak_usage() / 1024 / 1024 . ' MB'; // Peak usage
What is a reasonable memory_limit value for production?
128M–256M is typical for most PHP apps. WordPress recommends 40M, Laravel often needs 128M+. Set it to the minimum value your application needs.
Can memory exhaustion be caused by a single line of code?
Yes — loading a file with file_get_contents() on a 2GB file or fetching every row from a million-row table with fetchAll() can exhaust memory in one line.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro