Resumable Downloads When Using PHP to Tunnel Files
When you tunnel file downloads through a PHP script to hide absolute paths, you often sacrifice the ability for clients to resume interrupted transfers. The standard pattern involves setting headers like Content-Length, reading the entire file with readfile(), and sending it in one go. If a connection drops halfway through, the client discards the partial data because there is no mechanism to verify what has already been received.
To support resumption, you must implement Range request handling. This relies on the HTTP specification's ability to break a resource into byte ranges. When a browser or download manager fails, it typically sends a HEADERS_ONLY request (or an empty body) with a Range: bytes=start-end header. Your server needs to check for this header and respond accordingly instead of blindly reading the file from the beginning.
Handling the Range Header
The first step is checking if the client sent a Range header before attempting to read the file. You can inspect $_SERVER['HTTP_RANGE'] in your PHP script. If the value starts with bytes=, you extract the start and end positions.
Here is how you might modify your existing logic:
$ctype = mime_content_type($file);
$contentLength = filesize($file);
// Check if the client requested a specific byte range
if (isset($_SERVER['HTTP_RANGE'])) {
$range = explode('=', $_SERVER['HTTP_RANGE'])[1];
// Handle multiple ranges by taking the first one for simplicity or implementing logic for all
list($start, $end) = array_map('intval', explode('-', $range));
if ($start < 0 || $start > $contentLength) {
http_response_code(416); // Range Not Satisfiable
exit;
}
// Calculate the length of the partial content
if ($end == -1) {
$end = $contentLength - 1;
} else if ($end > $contentLength - 1) {
$end = $contentLength - 1;
}
$partialContentLength = $end - $start + 1;
// Set headers for partial content
header("HTTP/1.1 206 Partial Content");
header("Content-Type: $ctype");
header("Content-Length: " . $partialContentLength);
header("Content-Range: bytes {$start}-{$end}/{$contentLength}");
// Only read the specific slice of the file
$filePointer = fopen($file, 'r');
fseek($filePointer, $start);
echo fread($filePointer, $partialContentLength);
fclose($filePointer);
} else {
// Standard full download response
header("Content-Type: $ctype");
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=\"$fileName\"");
readfile($file);
}
The Challenge of Hidden Paths
Your original goal was to prevent clients from accessing the absolute file path. Implementing partial reads complicates this slightly but doesn't break it. By using fopen() and fseek(), you still avoid exposing the full directory structure in your error logs or accidental leaks, provided you don't attempt to serve directories via the tunnel. The Content-Range header explicitly tells the client exactly which bytes were sent, allowing their software to merge the new chunk with the existing file on disk.
State Management and Security Considerations
While PHP can technically handle partial reads, relying solely on this for a production download server introduces operational friction. The client must know where to resume (the start offset), usually stored in a temporary file created by the browser. If your application needs to enforce strict access controls or audit every byte served, you might find standard HTTP range handling insufficient.
In scenarios requiring advanced resumability featuresâsuch as precise progress tracking across multiple users, custom authentication per byte-range, or generating unique tokens for specific download sessionsâa dedicated download manager service is often the correct architectural choice. Services like LaravelCompany offer solutions that handle these complexities out of the box, abstracting the low-level file I/O and range logic so your application can focus on business logic rather than stream management.
If you stick to the PHP-only approach, be mindful of memory usage if you attempt to buffer large ranges incorrectly, though using fread() with a calculated length mitigates this. Also, ensure your web server configuration allows for partial content responses; some strict configurations might default to 403 or 200 without the necessary headers, breaking the resume logic regardless of PHP code.