PHP Fatal Error: Allowed Memory Size Exhausted (How to Fix It Properly)

PHP Fatal error: Allowed memory size exhausted and how to fix it

Quick answer: The script tried to use more memory than PHP's memory_limit allows. The usual causes are loading a whole query result, file or API response into memory, loops that keep accumulating data, and processing large images. Raising memory_limit (in php.ini, the PHP-FPM pool or .user.ini) is a short-term fix; the real fix is processing data in chunks: paginate queries, read files line by line, use generators and free what you no longer need.

The full message looks like this:

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted
(tried to allocate 20480 bytes) in /var/www/site/report.php on line 42

It usually shows up during imports, exports, reports, image uploads, or after a table grows. Here is how to read it, where to raise the limit when that is justified, and how to fix the code so the error doesn't come back.

Reading the message

  • 134217728 bytes is the current limit: 128 MB (134,217,728 / 1024 / 1024). 268435456 is 256 MB, 536870912 is 512 MB;
  • tried to allocate 20480 bytes is just the last small allocation that crossed the line, not the size of the problem;
  • the file and line show where memory ran out, which is often inside the loop or function that accumulates data, but not always where the data was loaded.

If the limit in the message is much lower than you expect, PHP is reading a different configuration than the one you edited (see below).

Common causes

  • Fetching a whole table: fetchAll() on hundreds of thousands of rows;
  • Reading whole files: file_get_contents() or file() on a large CSV, log or JSON;
  • Accumulating in loops: appending every row to an array or a string that is never released;
  • Large images: GD and Imagick decode the full bitmap, so a 6000 x 4000 photo needs around 100 MB regardless of its file size;
  • Infinite recursion or loops;
  • Heavy plugins or libraries (common on WordPress and with Composer).

Step 1: check the current limit

<?php
echo ini_get('memory_limit');                       // e.g. 128M
echo memory_get_peak_usage(true) / 1048576, ' MB';  // peak used so far

On the command line, php -i | grep memory_limit shows the CLI value, which is often different from the web server's (the CLI is commonly unlimited, -1). Also run php --ini to see which php.ini files are loaded.

Step 2: raise the limit in the right place

Where to change it depends on how PHP runs:

SetupWhereApply with
Anyphp.ini: memory_limit = 256MRestart PHP-FPM or Apache
PHP-FPM, one sitePool file: php_admin_value[memory_limit] = 256Msystemctl reload php-fpm
Apache with mod_php.htaccess: php_value memory_limit 256MImmediate
PHP-FPM / CGI, shared hosting.user.ini in the site root: memory_limit = 256MWithin a few minutes
One script onlyini_set('memory_limit', '512M'); at the topImmediate
WordPresswp-config.php: define('WP_MEMORY_LIMIT', '256M');Immediate (up to the server limit)

Two warnings: php_value in .htaccess causes a 500 error on servers running PHP-FPM, so use .user.ini there; and a host may block ini_set or cap the value. Avoid memory_limit = -1 on a web server: one runaway request can then exhaust the whole machine.

Raising the limit is fine when the job really needs more memory, like a monthly export. If memory keeps growing with your data, you'll hit the new limit too: fix the code.

Step 3: fix the code

Paginate or stream database results

Instead of loading everything:

<?php
$rows = $pdo->query('SELECT * FROM orders')->fetchAll();   // every row in memory at once

process in batches, using the primary key so each query stays fast:

<?php
$lastId = 0;
$stmt = $pdo->prepare('SELECT id, customer, total FROM orders WHERE id > :last ORDER BY id LIMIT 1000');

do {
    $stmt->bindValue(':last', $lastId, PDO::PARAM_INT);
    $stmt->execute();
    $batch = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($batch as $row) {
        processOrder($row);
        $lastId = $row['id'];
    }
} while (count($batch) === 1000);

Select only the columns you need: SELECT * on a table with text columns multiplies memory use. For a single long pass, MySQL can also stream rows without buffering them in PHP, by turning off buffered queries for that connection: $pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);.

Read files line by line

<?php
$handle = fopen('import.csv', 'r');
while (($line = fgetcsv($handle)) !== false) {
    importRow($line);   // one line in memory at a time
}
fclose($handle);

For downloads, write output as you go (or stream the file with readfile()) instead of building a huge string.

Use generators

A generator returns one item at a time instead of a full array:

<?php
function readLines(string $path): Generator
{
    $h = fopen($path, 'r');
    while (($line = fgets($h)) !== false) {
        yield rtrim($line, "\r\n");
    }
    fclose($h);
}

foreach (readLines('/var/log/app.log') as $line) {
    // only one line in memory
}

Shrink images before processing

GD needs roughly width x height x 4 bytes (plus overhead) for each image in memory. Reject or downscale huge uploads before working on them, check dimensions with getimagesize() first, and call imagedestroy() when done. See secure file uploads in PHP.

Free memory in long loops

<?php
foreach ($ids as $id) {
    $report = buildReport($id);
    saveReport($report);
    unset($report);   // release before the next iteration
}

In long-running workers and CLI jobs, watch memory_get_usage() per iteration: if it keeps rising, something is holding references (a static cache, an ORM identity map, a growing log array).

Composer and WordPress

  • Composer: run COMPOSER_MEMORY_LIMIT=-1 composer update (on the command line only), or better, run composer update locally and only composer install on the server;
  • WordPress: WP_MEMORY_LIMIT for the site and WP_MAX_MEMORY_LIMIT for the admin; if the error persists, disable plugins one by one to find the one consuming memory.

Memory error vs. server out of memory

"Allowed memory size exhausted" is PHP's own limit per request. If the server itself runs out of RAM, the kernel kills processes instead, and you see 502 errors or PHP-FPM restarts rather than this message. See 502 Bad Gateway.

Checklist

  • Read the limit and the file/line in the message;
  • Confirm which php.ini or pool the web server uses;
  • Raise the limit only as much as the task needs;
  • Paginate or stream queries and select only needed columns;
  • Read files line by line, use generators;
  • Downscale images before processing;
  • Release large variables in loops;
  • Log errors instead of displaying them (see finding PHP errors in the logs).

Conclusion

"Allowed memory size exhausted" means a script outgrew memory_limit. Raising the limit buys time, but the lasting fix is processing data in pieces: batches from the database, lines from files and images at a reasonable size. Code written that way keeps working no matter how much the data grows.

Frequently asked questions

What does "Allowed memory size of 134217728 bytes exhausted" mean?

The script reached PHP's memory limit of 128 MB.

I changed php.ini and nothing happened. Why?

You probably edited the CLI php.ini, or didn't restart PHP-FPM or Apache. Check with phpinfo() in the browser which file is loaded and what value is active.

Is memory_limit = -1 safe?

On the command line for a one-off task, usually. On a web server, no: a single bad request can use all the server's memory.

Why does a small image cause the error?

Image libraries work on the decoded bitmap. A 2 MB JPEG with 24 million pixels needs about 100 MB in memory.

Why does .htaccess give a 500 error when I set memory_limit?

php_value only works with mod_php. On PHP-FPM, use .user.ini or the pool configuration.

More in PHP