Home >Backend Development >PHP Tutorial >How Can I Enable Resumable Downloads with a PHP Script?
Supporting Resumable Downloads with PHP Scripting
Question:
When using a PHP script to send downloadable files, downloads cannot be resumed by end users. How can resumable downloads be supported with such a solution?
Answer:
To enable resumable downloads, follow these steps:
Send the Accept-Ranges: bytes header:
Handle range headers:
Set partial content headers:
If the request is for a partial content (Range header is present), set the following headers:
Send the file data:
Here's a sample PHP code that demonstrates how to implement partial content downloads:
$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 ($offset > 0) { header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize); } header('Content-Type: ' . $ctype); header('Content-Length: ' . $length); header('Content-Disposition: attachment; filename="' . $fileName . '"'); header('Accept-Ranges: bytes'); print($data);
This code sets the appropriate headers and responds with the requested file data, supporting resumable downloads.
The above is the detailed content of How Can I Enable Resumable Downloads with a PHP Script?. For more information, please follow other related articles on the PHP Chinese website!