Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Node.js, PHP and APIs

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 show

Fix it fast

Most common cause, 1 of 3

A 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.

Fix
<?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
}
Did this fix it?
Full steps for this cause: check, fix, verify

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.

  • Applies to PHP 8.2-8.6
  • Updated
  • By Maaz Zindani, Senior Software Engineer

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).

Run this first
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:

  1. 1A large local file is read whole to process its linesfile_get_contents() or file() opens a CSV, log or export of hundreds of megabytes, and the code then splits it into lines
  2. 2The file is echoed to the browser as one stringA download or media endpoint does echo file_get_contents($path), or calls readfile() while output buffering is active
  3. 3A remote file is downloaded into a string before it is savedThe 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.

Check
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.

Fix
<?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.

Verify
echo round(memory_get_peak_usage(true) / 1048576) . " MB\n";

Confirmed by php.net

Did this fix it?

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.

Check
// in the download endpoint, just before sending
var_dump(ob_get_level()); // 0 means no output buffer is active

Fix

Close every open output buffer, send the headers, then stream the file with readfile() and stop.

Fix
<?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.

Verify
curl -s -o /dev/null -w '%{http_code} %{size_download}\n' https://example.com/download/42

Confirmed by php.net

Did this fix it?

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.

Check
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().

Fix
<?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.

Verify
echo filesize($target), ' bytes, peak ', memory_get_peak_usage(true), PHP_EOL;

Confirmed by php.net

Did this fix it?

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

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.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.