DEV Community

Raja Hunain
Raja Hunain

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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) {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

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
    }
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

And check the live value inside the code that is failing:

echo ini_get('memory_limit');
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The number that frames the whole list is right in the error: 134217728 bytes — the default 128 MB — and your point that raising memory_limit only buys time is the part most people learn the expensive way. The fix I would steal first is the chunk(500) pattern, because it turns an unbounded problem into a flat one: memory stays roughly flat no matter how many rows the table holds, which is exactly the shape a report or export needs. The one I have seen bite hardest in practice is number 2 — CLI and PHP-FPM reading different php.ini files, so the limit you raised is not the limit the failing request reads. Which of the five has bitten you most often in real projects — the all() load, or the long-running worker cache that only grows between jobs?