file_get_contents() runs out of memory on large files and downloads
Your error
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 536870920 bytes)1 more line it can showFix it fast
Most common cause, 1 of 3A large local file is read whole to process its lines
Iterate over the file with SplFileObject, which hands out one line or CSV row at a time, so memory stays roughly the size of one row.
<?php
$file = new SplFileObject('storage/import.csv');
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY);
foreach ($file as $row) {
importRow($row); // one row in memory at a time
}Short answer
Allowed memory size of ... bytes exhausted on a file_get_contents() line means a whole file or download is being held in one PHP string. Read big files line by line, send files to the browser with readfile() and output buffering off, and save remote files by handing a stream to file_put_contents(). A higher memory_limit only moves the ceiling. Applies to PHP 8.2-8.6.
Which cause do you have?
Compare the size of the file with the limit and with the tried to allocate figure in the error. A number close to the file size confirms the whole file is loaded. Then see what the code does with the string: processes it (cause 1), echoes it to the browser (cause 2) or writes it to disk (cause 3).
php -r 'echo filesize("storage/import.csv"), " bytes; limit ", ini_get("memory_limit"), PHP_EOL;'
grep -rn "file_get_contents(" src/Then find the line you see in this list and open its fix:
- 1A large local file is read whole to process its lines
file_get_contents() or file() opens a CSV, log or export of hundreds of megabytes, and the code then splits it into lines - 2The file is echoed to the browser as one string
A download or media endpoint does echo file_get_contents($path), or calls readfile() while output buffering is active - 3A remote file is downloaded into a string before it is saved
The code does file_put_contents($target, file_get_contents($url)) for a large export, video or backup
What does the error look like?
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 536870920 bytes)Fatal error: Allowed memory size of 268435456 bytes exhausted
Cause 1 of 3
A large local file is read whole to process its lines
You seefile_get_contents() or file() opens a CSV, log or export of hundreds of megabytes, and the code then splits it into lines
Check
The PHP manual describes file_get_contents() as reading the entire file into a string, so a 500 MB import needs at least that much memory before the first row is touched, and splitting it with explode() builds an array of every line on top of that string. With the default memory_limit of 128M the script dies on that line.
grep -rnE "explode\(.*file_get_contents|file\(" src/Fix
Iterate over the file with SplFileObject, which hands out one line or CSV row at a time, so memory stays roughly the size of one row.
<?php
$file = new SplFileObject('storage/import.csv');
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY);
foreach ($file as $row) {
importRow($row); // one row in memory at a time
}Verify
The import finishes under the original limit; print the peak at the end to see the difference.
echo round(memory_get_peak_usage(true) / 1048576) . " MB\n";Confirmed by php.net
Cause 2 of 3
The file is echoed to the browser as one string
You seeA download or media endpoint does echo file_get_contents($path), or calls readfile() while output buffering is active
Check
Sending a file with echo file_get_contents() first copies all of it into memory. readfile() streams it instead, and its manual page says it causes no memory issues on its own; if it still runs out of memory, an active output buffer is collecting the bytes, which ob_get_level() reveals.
// in the download endpoint, just before sending
var_dump(ob_get_level()); // 0 means no output buffer is activeFix
Close every open output buffer, send the headers, then stream the file with readfile() and stop.
<?php
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Content-Length: ' . filesize($path));
readfile($path);
exit;Verify
A download of a file larger than memory_limit completes, and the PHP error log shows no fatal error.
curl -s -o /dev/null -w '%{http_code} %{size_download}\n' https://example.com/download/42Confirmed by php.net
Cause 3 of 3
A remote file is downloaded into a string before it is saved
You seeThe code does file_put_contents($target, file_get_contents($url)) for a large export, video or backup
Check
Fetching a URL with file_get_contents() buffers the whole response in memory before anything reaches disk. The PHP manual notes that file_put_contents() also accepts a stream resource and then copies the remaining data of that stream to the file, much like stream_copy_to_stream(), so the response never has to fit in memory.
grep -rn "file_put_contents(.*file_get_contents(" src/Fix
Open the URL as a stream with fopen() and pass that stream to file_put_contents().
<?php
$in = fopen($url, 'rb');
if ($in === false) {
throw new RuntimeException("Cannot open $url");
}
$bytes = file_put_contents($target, $in);
fclose($in);Verify
The saved file has the expected size, and peak memory stays far below the file size.
echo filesize($target), ' bytes, peak ', memory_get_peak_usage(true), PHP_EOL;Confirmed by php.net
How do I stop it coming back?
- Treat file_get_contents() as a small-file function: config, templates and API bodies, not imports or media.
- Put a size check in front of any code path that loads a user-supplied file into memory, and switch to streaming above a set size.
- Record the peak memory of every import and download job in its log line, so a file that keeps growing is noticed well before it hits the limit.
Sources
- PHP manual: file_get_contents
- PHP manual: SplFileObject (READ_CSV, READ_AHEAD, SKIP_EMPTY)
- PHP manual: readfile (memory note)
- PHP manual: file_put_contents (stream resource as data)
- PHP manual: ob_get_level
- PHP manual: core php.ini directives (memory_limit 128M)
- php-src: Zend/zend_alloc.c (the memory error text)
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 on the same stack: Spotless Laundry, EZ Estimater.