Home > Backend Development > PHP Tutorial > How Can PHP Implement Resumable File Downloads?

How Can PHP Implement Resumable File Downloads?

Linda Hamilton
Release: 2024-12-07 11:10:17
Original
902 people have browsed it

How Can PHP Implement Resumable File Downloads?

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

Additional Notes

  • The code assumes that only a single range is requested.
  • Error handling has been omitted for brevity.
  • Refer to the provided documentation for further details on partial content and the fread function.

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!

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