PHP Fatal error: Allowed memory size of 134217728 bytes exhausted
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)Short answer
The script used more memory than memory_limit allows. 134217728 bytes is 128M, PHP's built-in default. Measure peak usage first. If the job is legitimately big, raise memory_limit where PHP reads it. If it loads everything into an array, process it one item at a time with a generator.
Fix it fast
1Find out which cause you have
Print the limit in force for the process that failed and the peak the script reached. Put the second line at the end of the script, or in a shutdown function.
php -i | grep memory_limit // in code: echo memory_get_peak_usage(true) / 1048576 . " MB\n";2Match what you see, then jump to its fix
- 1
(tried to allocate N bytes) with a small N, after the script ran for a while on real dataThe job is bigger than the default 128MFix - 2
You edited a php.ini but the same limit appears in the errorThe change was made in a place the failing process does not readFix - 3
The limit is already high (512M or more) and it still runs out, growing with the input sizeThe code builds a huge array before using itFix - 4
The error appears on a form or upload endpoint, with large post_max_sizeUploads or posted data are larger than memory_limit allowsFix
- 1
What does the error look like?
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)PHP Fatal error: Allowed memory size of 268435456 bytes exhausted
Cause 1 of 4
The job is bigger than the default 128M
1Check
memory_limit defaults to 128M. Image resizing, big imports and large exports can honestly need more. Compare the peak with the limit.
<?php
register_shutdown_function(function () {
error_log('peak MB: ' . memory_get_peak_usage(true) / 1048576);
});2Fix
Raise the limit in php.ini for the SAPI that runs the job. Use a number, not -1, which removes the limit and lets a runaway script eat the whole server.
; php.ini
memory_limit = 256M3Verify
Restart PHP-FPM or Apache, confirm the new value and rerun the job.
sudo systemctl restart php8.3-fpm
php -r 'echo ini_get("memory_limit"), PHP_EOL;'Confirmed by php.net
Cause 2 of 4
The change was made in a place the failing process does not read
1Check
The CLI and the web server can load different php.ini files. .user.ini is read only by CGI/FastCGI, and Apache with mod_php needs .htaccess instead. A .user.ini edit can also take up to 300 seconds to apply, because of user_ini.cache_ttl.
php --ini
php -i | grep -i "user_ini"2Fix
Edit the file that belongs to the SAPI that failed. For per-site settings on PHP-FPM, use .user.ini next to the site's index.php.
; .user.ini
memory_limit = 256M3Verify
Load a page that prints ini_get('memory_limit') after the cache time has passed.
php -r 'echo ini_get("memory_limit"), PHP_EOL;'Confirmed by php.net
Cause 3 of 4
The code builds a huge array before using it
1Check
Look for range(), file(), fetchAll() or a query that loads every row. A generator hands out one value at a time, so memory stays flat as the input grows.
grep -rn -E "fetchAll|file\(|range\(" src/ | head2Fix
Read and process items in a loop that yields one at a time, instead of returning the full array.
<?php
function readLines(string $path): Generator {
$h = fopen($path, 'r');
while (($line = fgets($h)) !== false) {
yield $line;
}
fclose($h);
}
foreach (readLines('big.csv') as $line) {
// handle one line
}3Verify
Rerun with the original limit and compare memory_get_peak_usage() before and after.
php import.phpConfirmed by php.net
Cause 4 of 4
Uploads or posted data are larger than memory_limit allows
1Check
The manual says memory_limit should be larger than post_max_size. A post_max_size set above the memory limit invites this failure.
php -i | grep -E '^(post_max_size|memory_limit|upload_max_filesize) '2Fix
Keep memory_limit above post_max_size, and post_max_size above upload_max_filesize.
; php.ini
upload_max_filesize = 20M
post_max_size = 25M
memory_limit = 256M3Verify
Upload a file near the limit and check the log.
sudo tail -n 20 /var/log/php/error.logConfirmed by php.net
How do I stop it coming back?
- Log memory_get_peak_usage() at the end of heavy jobs so growth shows up before the limit is hit.
- Process large files and result sets in batches or with generators.
- Give queue workers and cron jobs their own limit, separate from web requests.
- Avoid memory_limit = -1 on shared or production servers.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack end
Apache returns 403 when a URL contains %3F
a request like /page%3Fname=test is refused while /page?name=test works
Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.
2 causes, each with a fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fixBack end
AWS SDK for PHP rejects requests: the signature is from the future
Signature not yet current: {date} is still later than {date}
AWS compares the timestamp in your signed request with its own clock.
2 causes, each with a fix