Skip to content

PHP Fatal Error: Allowed Memory Size Exhausted Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about PHP Fatal Error: Allowed Memory Size Exhausted Fix. We cover key concepts, practical examples, and best practices.

The Problem

Your PHP script crashes with:

Fatal error: Allowed memory size of 134217728 bytes (128 MB) exhausted (tried to allocate 20480 bytes) in /var/www/html/index.php on line 42

PHP enforces a per-script memory limit (default 128 MB). When your script allocates more memory than the limit, PHP throws a fatal error and halts execution. This often happens when processing large files, running unbounded loops, or leaking memory.

Quick Fix

Step 1: Find the memory-heavy operation

Check which part of your code uses the most memory:

php -d memory_limit=256M my_script.php

Add memory profiling at suspected points:

echo 'Memory: ' . round(memory_get_usage() / 1024 / 1024, 2) . " MB\n";
echo 'Peak: ' . round(memory_get_peak_usage() / 1024 / 1024, 2) . " MB\n";

Step 2: Fix infinite loops

WRONG -- loop that never terminates:

$data = [];
while (true) {
    $data[] = str_repeat('x', 1024);  // grows forever
    if (count($data) > 1000) break;   // unreachable
}

RIGHT -- add a proper termination condition:

$data = [];
for ($i = 0; $i < 1000; $i++) {
    $data[] = str_repeat('x', 1024);
}

Step 3: Process large files in chunks

WRONG -- loading entire file into memory:

$lines = file('large_file.csv');  // loads whole file into an array
foreach ($lines as $line) {
    process($line);
}

RIGHT -- stream the file line by line:

$handle = fopen('large_file.csv', 'r');
while (($line = fgets($handle)) !== false) {
    process($line);
}
fclose($handle);

Step 4: Free memory explicitly

WRONG -- holding references to large data:

$largeData = fetchLargeDataset();
$result = process($largeData);
// $largeData still in memory for rest of script
$moreData = fetchMoreData();  // memory exhausted

RIGHT -- unset variables when done:

$largeData = fetchLargeDataset();
$result = process($largeData);
unset($largeData);  // free memory
$moreData = fetchMoreData();

Step 5: Increase memory limit (temporary fix)

WRONG -- hard-coding memory limit in the script:

ini_set('memory_limit', '-1');  // unlimited -- dangerous!

RIGHT -- set a reasonable limit:

ini_set('memory_limit', '512M');  // increase from 128M to 512M

Or set it globally in php.ini:

memory_limit = 512M

Check the current limit:

php -i | grep memory_limit

Step 6: Optimize database queries

Loading all rows from a large table into memory:

WRONG -- fetching everything at once:

$users = $db->query("SELECT * FROM users")->fetchAll();  // memory heavy

RIGHT -- use pagination or streaming:

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

Use DodaTech's PHP Profiler to track memory usage per function call and identify memory leaks in long-running scripts.

Prevention

  • Process large datasets in chunks (pagination, streaming).
  • Use generators (yield) for iterating over large collections.
  • Unset large variables as soon as they are no longer needed.
  • Monitor memory usage with memory_get_usage() in production.
  • Set a realistic memory_limit in php.ini (128M-512M for most apps).
  • Use ob_start() and ob_flush() to manage output buffer memory.

Common Mistakes with fatal error

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world PHP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the default PHP memory limit?

The default is 128 MB for most PHP installations. You can check it with php -i | grep memory_limit or echo ini_get('memory_limit'); from a script.

Can I set memory_limit to -1 in production?

No. Unlimited memory allows a single misbehaving script to consume all server memory, causing OOM kills and crashing other services. Always set a finite limit.

Why does memory_get_usage() show less than the memory limit when I get a fatal error?

memory_get_usage() reports memory allocated by PHP's internal memory manager, not the total process memory. PHP may allocate additional memory behind the scenes (e.g., for the Zend engine, internal buffers) that is not counted.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro