Why the download proxy streams in chunks instead of readfile

2026-12-03来源 dev.toEnglish

When I first built the download proxy for ramrom.io, I did the obvious thing. PHP has a function called readfile(). You give it a URL or a path, it reads the whole file and sends it to the browser. One line, done. It worked perfectly in testing — until someone pasted a video that was a few hundred megabytes.

The problem is how readfile() actually works. It loads the whole file into memory before it sends anything. On a local machine with plenty of RAM, nobody notices. On a shared hosting plan, the PHP process is capped at a modest memory limit — mine is 128MB — and a single 300MB video blows straight past it. The visitor gets a blank page or a half-finished file, and the server logs a fatal error that tells me nothing useful.

So I rewrote the proxy to stream in chunks. The shape of it is simple, and I have kept it that way on purpose:

$context = stream_context_create([ 'http' => [ 'method' => 'GET', 'header' => "User-Agent: Mozilla/5.0\r\n", 'timeout' => 30, ], ]); $stream = fopen($remoteUrl, 'rb', false, $context); if ($stream === false) { http_response_code(502); exit('The video could not be fetched. Please try again.'); } while (!feof($stream)) { echo fread($stream, 8192); flush(); } fclose($stream); 

That 8KB number is not magic. It is small enough that memory usage stays flat no matter how big the file is, and large enough that the loop is not doing silly amounts of work. The memory graph of a 500MB download now looks exactly like the graph of a 5MB one: a flat line. That is the whole point. The file size stops being a variable I have to care about.

There are a few details around the loop that matter as much as the loop itself.

First, set_time_limit(). A chunked download of a large file takes a while, and PHP's default script timeout will kill the process mid-stream. I raise the limit for the proxy endpoint only, and I cap it so a stalled download cannot hang forever. The proxy has a 30-second ceiling on the upstream fetch, so a genuinely enormous file fails honestly rather than hanging. I would rather show an honest error than a spinner that never ends.

Second, ignore_user_abort(). If a visitor closes the tab mid-download, PHP's default behaviour is to kill the script. On the proxy I set it so the stream finishes cleanly instead. It is a small courtesy to the browser, and it stops half-finished connections from piling up.

Third, output buffering. PHP can buffer output before sending it, which defeats the entire point of streaming: the chunks pile up in a buffer until the whole file is sitting in memory again. I turn buffering off for the proxy and call flush() after every chunk so the bytes leave the server as they are read. This is the one line that broke my MP4s for a day — a stray ob_start() in a shared include file meant downloads were arriving corrupt. The fix was one line, but finding it took an afternoon of staring at hex dumps.

Fourth, headers. Before the first chunk leaves, the proxy sends the right Content-Type and a Content-Disposition: attachment header so the browser downloads the file instead of playing it in the tab. If the upstream sent a Content-Length, I pass it through so the browser can show a real progress bar. If it did not, I send nothing — honest either way.

The rule I ended up with is simple: a proxy should never hold more of a file than the size of one chunk. The moment it does, file size becomes your problem, and on shared hosting file size will always win that fight eventually. Streaming in 8KB pieces turned a fatal error into a flat memory line, and it is the reason the proxy now handles files far larger than the server's memory limit without noticing.

Nothing here needs a framework, a queue, or a bigger server. It is one loop, a handful of settings, and a refusal to load the whole file into memory. That is usually enough.

原文:https://www.a8q9.cn/en/article/why-the-download-proxy-streams-in-chunks-instead-of-readfile-8cb58f.html

相关文章