ENGINEERING JOURNAL

PHP "Allowed Memory Size Exhausted": Finding the Leak

PHP "Allowed memory size exhausted" is a symptom, not the diagnosis. Learn to find the leak, fix the code, and know when raising the limit is the honest fix.

THE ARTICLE 01 — 02

A PHP script dies with "Allowed memory size of 134217728 bytes exhausted" and the first instinct is to raise memory_limit. Sometimes that is the right call. Most of the time it just buys you a bigger crash a few hours later. The error is a symptom, not the diagnosis. Here is how I track down what is actually eating the memory, and how I decide whether to fix the code or raise the limit.

Read the error message properly

The fatal error tells you three things: the limit that was hit, how much memory the script had already allocated when it failed, and the file and line where the allocation happened. That line is where the request died, not necessarily where the leak lives. A script that loads 100,000 rows into an array will die on the line that fetches row 100,001, but the real problem is the design decision to load every row at once. Note the numbers first, then look upstream for what grew the memory.

Check the limit before you change it

Find out which limit is actually in effect. The value in php.ini is not always the value your script sees. On shared hosting, a local php.ini, an .htaccess directive, or a per-directory setting can override it. Run this from the same environment the script runs in:

php -r "echo ini_get('memory_limit'), PHP_EOL;"
php -i | grep -i "memory_limit"

On a web request, a quick phpinfo() page (delete it right after) shows the loaded configuration file and any local overrides. I have seen scripts die at 128M while the server-wide limit was 256M, because a stale .user.ini in the project root capped it. Fix the setting that is actually active, not the one you assume is active.

Find the growth, not just the peak

Memory problems come in two shapes: a single huge allocation, or slow growth over a loop. A few memory_get_usage() calls tell you which one you have:

$start = memory_get_usage(true);
foreach ($records as $record) {
    process($record);
    if ($i % 1000 === 0) {
        error_log(sprintf('row %d: %s MB', $i, round(memory_get_usage(true) / 1024 / 1024, 1)));
    }
}

If memory climbs steadily with each iteration, something is accumulating: an array that is never cleared, a query log that keeps every statement, or an ORM that holds every model it loads. If it jumps once, look for a single large read, like fetching a whole table or decoding a large JSON file into memory.

The usual suspects in Laravel and plain PHP

A few patterns cause most of the memory exhaustion I have seen:

  • Loading everything, then filtering. Model::all() on a big table, or file_get_contents() on a multi-megabyte file. Use chunk(), cursor(), or a streaming reader instead.
  • Query logging left on in a long-running job. Laravel keeps every executed query in memory when the query log is enabled. In a worker or a command that processes thousands of records, disable it with DB::disableQueryLog().
  • Debug output accumulating. Anything that appends to a growing string or array in a loop, including log buffers, will eventually hit the limit.
  • Recursive data or deep object graphs. Serializing an Eloquent model with loaded relations can pull in far more data than you expect. Select only the columns you need.

The chunked version of the first problem looks like this:

Order::where('status', 'pending')
    ->chunk(500, function ($orders) {
        foreach ($orders as $order) {
            process($order);
        }
    });

Five hundred rows at a time keeps memory roughly flat instead of growing with the table.

When raising the limit is the honest fix

Sometimes the code is fine and the limit is simply too small for the job. Generating a large PDF, exporting a CSV of a million rows, or processing an uploaded image legitimately needs more memory. In that case, raise the limit only for that script, not globally:

ini_set('memory_limit', '512M');

Put it at the top of the specific command or controller action, with a comment explaining why. A global raise hides the next real leak and, on shared hosting, can get your account throttled when several requests spike at once. If you need more than 512M for a routine web request, that is a design problem, not a configuration problem. Move the work to a queue job, where a higher limit and a longer timeout are expected. For the deployment side of this, my PHP shared hosting deployment checklist covers how memory limits and other PHP settings behave differently on shared hosting than on a VPS.

A repeatable checklist

Next time a script dies with this error, work through these steps in order:

  1. Read the fatal error: limit, allocated bytes, file and line.
  2. Confirm the effective memory_limit in the environment where the script actually runs.
  3. Log memory_get_usage() at intervals to see whether memory grows steadily or jumps once.
  4. Look for the usual suspects: full-table loads, query logging in long jobs, growing arrays in loops.
  5. Fix the code first. Raise the limit only for the specific script, and only when the workload genuinely needs it.

Raising the limit is a valid fix, but it should be a decision you make after measuring, not the first thing you try. The error message is telling you where the script ran out of room. Your job is to find out what filled the room.

Muhammad Aqib ← ALL ARTICLES
KEEP EXPLORING

More ideas.
Better engineering.

Explore the journal ↗