Resumable Downloads with PHP-Based File Tunneling
In this scenario, where PHP is used as a proxy for file downloads, users face challenges in resuming interrupted downloads. This article aims to address this issue and explore possible solutions.
Implementing Resumable Downloads in PHP
To enable resumable downloads, you must initially convey the server's support for partial content via the "Accept-Ranges: bytes" header. Subsequently, when a request includes the "Range: bytes=x-y" header (where x and y represent numerical values), you should extract the requested range and manipulate the file transfer accordingly.
The following PHP code accomplishes this:
$filesize = filesize($file); $offset = 0; $length = $filesize; if (isset($_SERVER['HTTP_RANGE'])) { preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches); $offset = intval($matches[1]); $length = intval($matches[2]) - $offset; } $file = fopen($file, 'r'); fseek($file, $offset); $data = fread($file, $length); fclose($file); if ($partialContent) { header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize); } header('Content-Type: ' . $ctype); header('Content-Length: ' . $filesize); header('Content-Disposition: attachment; filename="' . $fileName . '"'); header('Accept-Ranges: bytes'); print($data);
Additional Notes
The above is the detailed content of How Can PHP Implement Resumable File Downloads?. For more information, please follow other related articles on the PHP Chinese website!