5 PHP Memory Mistakes That Kill Your Script (and the Fix for Each)
If you have ever seen this in a PHP log, you know the feeling: Fatal error: Allowed memory size of 134217728 bytes exhausted The script stops dead. There is no graceful fallback, no catch block that saves it. An
If you have ever seen this in a PHP log, you know the feeling:
Fatal error: Allowed memory size of 134217728 bytes exhausted
The script stops dead. There is no graceful fallback, no catch block that saves it. And the usual first reaction — raising memory_limit — often only buys time. If the job keeps growing, it will hit the new limit too.
Here are five mistakes I see again and again, and the fix for each one.
1. Loading every row with get() / all()
This is the classic one. A report, an export, or a migration loads an entire table into an array before it does any work:
// Bad: every user in memory at once
$users = User::all();
foreach ($users as $user) {
// ...
}
Fix it by streaming the rows in chunks instead:
User::chunk(500, function ($users) {
foreach ($users as $user) {
// process one batch, then let it go
}
});
Memory stays roughly flat, no matter how many rows the table holds.
2. Raising the limit in the wrong place
CLI and PHP-FPM do not necessarily read the same php.ini. You can raise the limit in one place and watch the web request keep failing at the old value.
Check which file each runtime actually uses:
php --ini
And check the live value inside the code that is failing:
echo ini_get('memory_limit');
Change the limit in the file your runtime reads — and remember that a web server usually needs a restart or reload before the change takes effect.
3. Reading whole files into memory
file_get_contents() on a 70 MB log file puts the whole 70 MB in memory at once, before you have read a single line. Add the processing on top, and the limit is gone.
Stream it instead:
$handle = fopen('app.log', 'r');
while (($line = fgets($handle)) !== false) {
// process one line at a time
}
fclose($handle);
One line in memory at a time is a very different problem from the whole file.
4. Forgetting generators exist
When a function builds a big array and returns it, the whole result has to exist in memory before the caller sees the first item. A generator yields one row at a time:
function readRows(string $file): Generator
{
$handle = fopen($file, 'r');
while (($line = fgets($handle)) !== false) {
yield $line;
}
fclose($handle);
}
foreach (readRows('data.csv') as $row) {
// handle one row, then move on
}
The peak stays low because only the current row is held.
5. Caching inside a long-running worker
In a short request, a static property or an in-memory cache is harmless — the process dies and the memory is freed. In a long-running worker, those values accumulate across jobs. The worker slowly grows until it hits the limit in the middle of an ordinary job.
Restart workers regularly, clear per-job caches between jobs, and do not keep growing collections in static properties.
Measure before and after, so you are fixing a real problem instead of guessing:
echo memory_get_peak_usage(true);
The full walkthrough — how to read the three numbers in the error message, where to raise the limit correctly, and how to measure with memory_get_peak_usage() — is here: https://rajadevsolutions.online/errors/how-to-fix-allowed-memory-size-exhausted-error-in-php
Raise the limit when the job genuinely needs it. Fix the code when it keeps growing. That is the whole rule.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.