PHP Fatal error: Allowed memory size of 134217728 bytes exhausted — how to fix it
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate N bytes) means one PHP process reached its memory_limit, here 128M, PHP's default. Raise the limit for one run with php -d memory_limit=512M, in php.ini, or for Composer with COMPOSER_MEMORY_LIMIT; then fix what filled it, usually a query that loads every row at once or a response built in memory. In Laravel, chunk, lazy and streamed responses keep memory flat.
By Livops team, the people who build and run LivopsUpdated
The error, from a command line or a web request’s log (the numbers and paths vary):
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) in /var/www/html/app/Console/Commands/ExportUsers.php on line 31
Composer prints the same message when it runs out[6], and WordPress names it as the reason for its own memory setting[11]. This page explains what the two numbers mean, how to find which limit applies, how to raise it for one run, in php.ini, in code, for Composer and for WordPress, and then the fixes that make the error go away for good: loading rows in chunks, streaming large responses and keeping queue workers lean.
What does the error mean?
memory_limit is the maximum amount of memory, in bytes, that a script is allowed to allocate. It exists so that a badly written script cannot eat up all the memory on a server. Its default is 128M, and -1 means no limit[1]. In PHP’s shorthand, 1M is 1048576 bytes[2], so 128M is exactly 134217728 bytes: the number in the message is the default, untouched.
PHP writes the message as Allowed memory size of <limit> bytes exhausted (tried to allocate <size> bytes), where the first number is the limit and the second is the single allocation that would have crossed it[3]. A small second number does not mean a small problem: the process had already used nearly all of its memory, and this allocation was the last straw.
| The first number | Is | Usually set by |
|---|---|---|
134217728 |
128M | PHP’s default[1] |
268435456 |
256M | Someone raised it once |
536870912 |
512M | Someone raised it twice |
1610612736 |
1.5G | Composer, which raises its own limit to 1.5G[6] |
Two newer details. As of PHP 8.5.12, 8.4.27, 8.3.36 and 8.2.35, memory_limit is a soft limit: an allocation that crosses it is in most cases allowed to finish before the fatal error, and a separate hard limit, memory_hard_limit_percent, bounds how far it may go over[1]. And since PHP 8.5, a server can cap memory_limit with max_memory_limit; a higher value is cut down to the cap with a warning[1].
First, find which limit applies
The command line and the web server can read different configuration files. Check the value the command line gets[6], and which php.ini it loads[4]:
php -r "echo ini_get('memory_limit').PHP_EOL;"
php --ini
On Debian-like systems the command line has its own file, for example /etc/php5/cli/php.ini in Composer’s docs[6], so a web request may run with another value. To see what a request gets, print ini_get('memory_limit') from a route. To see how much the code really needs, log memory_get_peak_usage(true), the peak of memory allocated to the script, with true for the real size taken from the system[5].
Raising the limit
Raise it when the work is honest and just bigger than 128M: an import run once, a Composer update, a report. If the error moves to the next round number every month, go to the next section instead.
For one command
-d sets any php.ini directive for that run only[4]:
php -d memory_limit=512M artisan app:import-users
In php.ini
Change it in the file php --ini named, for the command line, the web server, or both:
memory_limit = 512M
In code
memory_limit can be changed anywhere, at runtime too[1], so a single heavy script can raise its own limit before the heavy part:
ini_set('memory_limit', '512M');
On PHP 8.5 a server’s max_memory_limit still caps it[1].
For Composer
Run Composer 2, if possible 2.2.0 or newer; Composer 1 used much more memory[6]. Composer raises its own limit to 1.5G[6]. When even that is not enough, set COMPOSER_MEMORY_LIMIT, whose value is used as PHP’s memory_limit[7], or pass -d[6]:
COMPOSER_MEMORY_LIMIT=-1 composer update
php -d memory_limit=-1 composer.phar update
These settings mainly cover Composer and its immediate processes; child processes or external commands it starts may need their own[6].
For WordPress
Set WP_MEMORY_LIMIT in wp-config.php, before the line that includes wp-settings.php; WP_MAX_MEMORY_LIMIT sets the limit for the admin area[11]:
define( 'WP_MEMORY_LIMIT', '256M' );
It raises PHP’s memory only for WordPress. By default WordPress tries to raise it to 40MB on a single site and 64MB on multisite, and some hosts do not allow raising it at all[11]. WordPress’s own docs warn that a higher limit can hide the cause, often too many memory-hungry functions on one action, which belong in a cron job[11].
The real fixes
Load rows in batches, not all at once
The most common cause in Laravel is Model::all() or ->get() on a big table. Laravel’s docs say an app may run out of memory loading tens of thousands of records that way[8]. chunk passes the rows to a callback a batch at a time, one query per batch; when you update the column you filter on, use chunkById, which pages by id[8]:
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
User::where('active', false)->chunkById(500, function (Collection $users) {
foreach ($users as $user) {
$user->update(['active' => true]);
}
}, column: 'id');
lazy runs the same batched queries but gives you one stream to loop over[8]:
foreach (User::lazy() as $user) {
// one batch in memory at a time
}
cursor runs a single query and holds one model in memory at a time, but cannot eager load relationships, and on very large results it can still run out because PHP’s PDO driver buffers the raw results; Laravel’s docs point to lazy there[8].
Stream large responses
An export built as one string or one array holds everything in memory before the first byte is sent. A streamed response sends data as it is generated, which Laravel’s docs say significantly reduces memory use for very large responses[9]. streamDownload turns output into a download without writing it to disk first[9]:
use App\Models\User;
use Illuminate\Support\Facades\Route;
Route::get('/users.csv', function () {
return response()->streamDownload(function () {
$out = fopen('php://output', 'w');
foreach (User::lazy() as $user) {
fputcsv($out, [$user->id, $user->email]);
}
fclose($out);
}, 'users.csv');
});
For JSON, response()->streamJson(['users' => User::cursor()]) sends a large dataset progressively[9].
Keep queue workers lean
A queue worker is long-lived and keeps the booted application in memory, and static state is not reset between jobs[10]. Memory that grows a little per job ends in this error after a few hours. --memory is the limit in megabytes at which the worker exits, 128 by default, or a percentage of memory_limit; --max-jobs and --max-time make it exit after a number of jobs or seconds, releasing what it accumulated[10]. Something has to start it again, such as Supervisor[10]:
php artisan queue:work --memory=256 --max-jobs=500
Free heavy resources after each job; Laravel’s docs give imagedestroy after GD image work as the example[10].
How to confirm the fix
Print the peak before and after the change, with the same data[5]:
logger()->info('peak MB: '.round(memory_get_peak_usage(true) / 1048576));
If the peak stays flat as the table grows, the code is fixed; if it grows with the table, a raised limit only buys time.
On Livops
- Two limits, two messages. This error is PHP’s
memory_limitinside one process. When the service itself runs out of memory, it is stopped, and Logs saysKilled, or exit code 137; see Out of memory. Raisingmemory_limitabove the service’s memory turns the first message into the second. - The service’s memory is a tier: 256, 512, 1024 or 2048 MiB.
memoryinlivops.jsonis read when the project is created; after that the tier is changed in the project’s settings, and it is part of what you pay for. See Frameworks and livops.json. - The assistant can propose changing a service’s memory as a card; it waits for your click. See AI assistant.
- Where the error shows. The start command Livops writes for a Laravel app begins with
LOG_CHANNEL=${LOG_CHANNEL:-stderr}, so what Laravel logs is on the service’s Logs tab. - Exports.
/tmpis wiped on every restart and holds 128 MB, so a large file built there first can fail too; stream it instead, as above. See Files and data.
The full Laravel setup on Livops, with the worker and the scheduler: Laravel hosting; plain PHP: PHP hosting. When Composer stops before memory is ever the problem: Your requirements could not be resolved to an installable set of packages.
Questions
Why exactly 134217728 bytes?
It is 128M written out in bytes. In PHP's shorthand one M is 1048576 bytes, and 128 times that is 134217728. 128M is the default memory_limit, so this number means nobody changed the limit for that process.
The message says tried to allocate only 20480 bytes. Why is that too much?
The second number is only the one allocation that would have crossed the limit, not the total. By then the process had already used almost all of its 128M. Look for what filled the memory before that line, not at the line itself.
Is memory_limit = -1 safe?
It removes PHP's limit. For a one-off command such as a Composer update on your own machine that is common, and Composer's docs show it. For web requests and long-running workers it is risky: the limit exists so that one badly written script cannot eat all the memory on the server.
Why does Composer still fail after I raised the limit?
Composer already raises its own limit to 1.5G, so a Composer error usually shows 1610612736 bytes, and only a higher value or -1 helps. COMPOSER_MEMORY_LIMIT and php -d memory_limit cover Composer itself and its immediate processes; an external command Composer starts may need its own setting.
Should I use chunk, lazy or cursor in Laravel?
chunk and chunkById pass the rows to a callback a batch at a time, lazy gives you the same batches as one stream, and cursor runs a single query and holds one model at a time. cursor cannot eager load relationships and can still run out of memory on very large results because PDO buffers them, so Laravel's docs point to lazy for those.
What is the difference between this error and Killed or exit code 137?
This error is PHP's own limit, memory_limit, inside one PHP process. Killed or exit code 137 means the whole container or machine ran out, and the operating system stopped the process. Raising memory_limit above the memory the machine has turns the first into the second.
How do I give a PHP app more memory on Livops?
Change the service's memory tier in its settings: 256, 512, 1024 or 2048 MiB. The tier is part of what you pay for. The assistant can also propose the change as a card, which waits for your click.
Sources
- PHP manual — Description of core php.ini directives (memory_limit) (php.net). Checked .
- PHP manual — FAQ, Using PHP (shorthand byte values) (php.net). Checked .
- PHP source — Zend/zend_alloc.c (github.com). Checked .
- PHP manual — Command line options (php.net). Checked .
- PHP manual — memory_get_peak_usage (php.net). Checked .
- Composer docs — Troubleshooting (Memory limit errors) (getcomposer.org). Checked .
- Composer docs — Command-line interface (COMPOSER_MEMORY_LIMIT) (getcomposer.org). Checked .
- Laravel docs — Eloquent, chunking and cursors (13.x, docs source) (github.com). Checked .
- Laravel docs — HTTP Responses, streamed responses (13.x, docs source) (github.com). Checked .
- Laravel docs — Queues, resource considerations (13.x, docs source) (github.com). Checked .
- WordPress Developer Resources — Editing wp-config.php (Increasing memory allocated to PHP) (developer.wordpress.org). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your PHP appRelated
- Composer: Your requirements could not be resolved to an installable set of packages — how to fix itYour requirements could not be resolved to an installable set of packages means Composer found no set of versions that fits composer.json and the machine it runs on. The Problem lines under it name the cause: Root composer.json requires php ^8.3 but your php version (8.2.x) does not satisfy that requirement is a PHP version mismatch, it is missing from your system is a missing extension, and the rest are conflicting constraints. Match PHP versions, set config.platform.php, install the extension, or find the blocker with composer why-not.
- Laravel hosting with queues and the scheduler: the options comparedA Laravel app in production is three processes: the web server, a queue worker that is restarted on every deploy, and the scheduler run every minute. On Livops the web app runs from a push with APP_KEY generated and migrations run, for 39 credits a month (39,000 so'm), and the worker and the scheduler are services of their own at 19 credits each. Here is how Render, Railway, Fly.io and a VPS compare.
- PHP hosting in 2026: how to deploy a PHP app or siteA PHP project is recognised from index.php or composer.json, its dependencies are installed, and it is served by FrankenPHP on the port Livops assigns. A plain folder of PHP files needs no configuration at all.
- Laravel: The stream or file laravel.log could not be opened in append mode: Permission deniedThe stream or file "storage/logs/laravel.log" could not be opened in append mode: Failed to open stream: Permission denied means the PHP process cannot write Laravel's log file: storage is owned by another user, the file was created by root, or the code runs on a read-only filesystem. Make storage and bootstrap/cache writable by the PHP user, or in a container log to stderr with LOG_CHANNEL=stderr. The bootstrap/cache directory must be present and writable is the same problem one folder over.
- JavaScript heap out of memory during next build: how to fix itNode's JavaScript heap reached its limit while Next.js was building, and V8 stopped the process. Raise the heap limit with NODE_OPTIONS=--max-old-space-size, staying below the memory the build really has, and cut what the build holds in memory: source maps, type checking during the build, and heavy dependencies.