Resolving 'Allowed Memory Size Exhausted' Errors in PHP
Learn how to diagnose and fix 'Allowed memory size exhausted' errors in PHP using memory checkpoints, stream processing, and generators to reduce footprints.
13 May 2026, 14:38 UTC

The Memory Exhaustion Problem
When a PHP script attempts to allocate more memory than the environment allows, the engine triggers a Fatal error: Allowed memory size of X bytes exhausted. This is a hard stop; the script terminates immediately, often leaving the user with a blank page or a 500 Internal Server Error.
The goal is not always to increase the limit, but to determine if the error is caused by a legitimate need for more resources or a memory leak—where memory is allocated but never released.
Diagnostic Matrix
| Symptom | Likely Cause | Diagnostic Indicator |
|---|---|---|
| Error occurs immediately on large file upload/read | Loading entire files into strings | file_get_contents() used on large files |
| Error occurs during database exports/imports | Fetching all rows into a single array | fetchAll() or large while loops without clearing variables |
| Memory climbs steadily in CLI scripts | Memory Leak | memory_get_usage() increases linearly over time |
| Error occurs randomly across different scripts | Global limit too low for environment | ini_get('memory_limit') is set to a very low value (e.g., 32M) |
Step-by-Step Memory Analysis
Follow these checks in order to isolate the cause before applying a fix.
1. Verify the Active Limit
Determine if the limit is being set globally in php.ini or overridden locally. Run this snippet in the environment where the error occurs:
If the limit is unexpectedly low, the issue may be a configuration error. If the limit is high (e.g., 256M or 512M) but the script still fails, you likely have a logic error or a massive dataset.
2. Locate the Memory Spike
Insert memory checkpoints around suspected blocks of code to find exactly where the usage jumps. Use memory_get_peak_usage() to see the highest point of allocation during the script's lifecycle.
Implementation Fixes
Option A: Stream-Based Processing (For Files)
If the diagnostic shows a spike during file reading, replace file_get_contents() with a stream. Streams read the file line-by-line, keeping memory usage constant regardless of file size.
Option B: Using Generators (For Datasets)
When iterating over large database results or arrays, avoid returning a full array. Use the yield keyword to create a Generator, which computes values on the fly.
query("SELECT * FROM logs")->fetchAll();
}
// Memory Efficient: Yields one item at a time
function get_records_generator($db) {
$stmt = $db->query("SELECT * FROM logs");
while ($row = $stmt->fetch()) {
yield $row;
}
}
// Usage
foreach (get_records_generator($db) as $record) {
// Memory stays flat here
echo $record['id'];
}
?>
Option C: Adjusting the Memory Limit
If the operation is legitimately resource-heavy and the server has physical RAM available, increase the limit. Avoid setting this globally in php.ini if only one script needs it.
- For a specific script: Use
ini_set('memory_limit', '256M');at the top of the file. - For the whole server: Edit
php.ini, setmemory_limit = 256M, and restart the PHP-FPM or Apache service.
Risk: Setting the limit to -1 (unlimited) in production can lead to a system-wide crash if a script enters an infinite loop, as the OS will trigger the OOM (Out of Memory) killer to protect the kernel.
Verification and Rollback
To verify the fix, run the script and monitor the output of memory_get_peak_usage(). A successful optimization (like switching to Generators) should show a peak memory value that remains stable even as the input dataset grows.
Rollback: If you modified php.ini, revert the memory_limit value to its previous state and restart the service to restore previous resource constraints.
Escalation Criteria
If the following conditions persist, move from code optimization to infrastructure analysis:
- Memory usage grows linearly in a CLI daemon despite using generators and
unset()on large variables. - The script crashes with a Segmentation Fault rather than a PHP Fatal Error.
- The server's physical RAM is exhausted (swap usage spikes) even when the PHP
memory_limitis not reached.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.