Home > Backend Development > PHP Tutorial > How Can I Enable Resumable Downloads with a PHP Script?

How Can I Enable Resumable Downloads with a PHP Script?

Susan Sarandon
Release: 2024-12-18 10:33:14
Original
863 people have browsed it

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:

  1. Send the Accept-Ranges: bytes header:

    • This header informs the client that you support partial content.
  2. Handle range headers:

    • If a request contains a Range: bytes=x-y header, parse it to determine the requested range.
    • Open the file, seek to the requested offset, and read the requested length of data.
  3. Set partial content headers:

    • If the request is for a partial content (Range header is present), set the following headers:

      • HTTP/1.1 206 Partial Content
      • Content-Range: bytes x-y/filesize
  4. Send the file data:

    • Output the requested data using print() or similar.

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template