PHP error guide
PHP "Allowed memory size exhausted": What It Means and How to Fix It
Error summary
The request exceeded `memory_limit`. Raise the limit only after reducing peak usage—unbounded arrays, huge file loads, and debug dumps are the usual causes.
What it means
The request exceeded memory_limit. Raise the limit only after reducing peak usage—unbounded arrays, huge file loads, and debug dumps are the usual causes.
What the error means
PHP’s memory manager refused a further allocation because the script hit the configured memory_limit for that SAPI.
Why PHP produces it
PHP isolates request memory so one runaway script cannot take the whole machine. Fatals occur at the allocation that crosses the limit.
PHP version notes
CLI and FPM often have different memory_limit values—verify with php -i vs a phpinfo page for the pool.
Most common causes
- Loading entire large files/result sets into arrays
- Infinite recursion or rapidly growing structures
- Composer/
vendoroperations with low CLI memory - Debug tools holding large object graphs
Minimal examples
BAD — reproduces the problem
$all = file_get_contents('/var/log/huge.log');\n$lines = explode(\"\\n\", $all);
FIXED — safer pattern
foreach (new SplFileObject('/var/log/huge.log') as $line) {\n // process\n}
Step-by-step diagnosis
- Note the byte limit in the message (e.g. 134217728 = 128M).
- Confirm which php.ini/
memory_limitapplies to the failing SAPI. - Profile the hot path—exports, image processing, ORM hydration.
- Check for accidental nested loops appending without bounds.
Fixes
Fix #1: Stream or chunk work
Process rows/files incrementally instead of building giant arrays.
$fh = fopen($path, 'rb');\nwhile (($line = fgets($fh)) !== false) {\n process_line($line);\n}\nfclose($fh);
Fix #2: Raise limit carefully
Increase memory_limit for a known heavy job, preferably per-script, after reducing usage.
ini_set('memory_limit', '256M'); // prefer pool/job-specific config in production
Common mistakes when fixing it
- Setting
memory_limit = -1globally in production - Raising limits forever instead of fixing a leak/unbounded export
How to prevent it
- Chunked exports and generators
- Memory budgets in CI for heavy commands
Web server / environment notes
FPM workers also constrained by system RAM and `pm.max_children`
Tags: cli,fpm,wordpress,composer