Skip to content

/errors/php/allowed-memory-size-exhausted

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate N bytes)

The commands on this page have not been executed by our verification runner yet.updated
tool
PHP
exit code
255
versions
PHP 7.x, PHP 8.x
os
any

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) means the script hit PHP's memory_limit. 134217728 bytes is 128 MB, the default; the "tried to allocate" number is only the last small allocation that failed, not the total needed. Either the job loads too much into memory at once (fix it by processing in chunks), or it really needs more and you raise memory_limit in php.ini or with ini_set(). In the error log the line starts with PHP Fatal error:, and the CLI exits with status 255.

Common values in the message

Bytes in the messagememory_limit
6710886464M
134217728128M (default)
268435456256M
536870912512M
10737418241G

Raise the limit

php.ini (or .user.ini for PHP-FPM / CGI)
memory_limit = 512M
php
<?php
ini_set('memory_limit', '512M');   // for this script only, before the heavy work
bash
php -d memory_limit=512M script.php           # one CLI run
php --ini                                     # which php.ini the CLI loads
php -r 'echo ini_get("memory_limit"), PHP_EOL;'
COMPOSER_MEMORY_LIMIT=-1 composer update      # Composer only

The CLI and the web server (PHP-FPM, Apache mod_php) usually load different php.ini files: change the one used by the process that fails, then restart PHP-FPM or the web server.

Use less memory instead

php
<?php
// Read a large file line by line instead of file() or file_get_contents()
$fh = fopen('big.csv', 'r');
while (($row = fgetcsv($fh)) !== false) {
    handle($row);
}
fclose($fh);

// Yield rows one at a time with a generator
function rows(PDO $db): Generator {
    $stmt = $db->query('SELECT * FROM events');
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        yield $row;
    }
}

Sources