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

How Can PHP Implement Resumable File Downloads?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 11:10:17943browse

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);

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!

Statement:
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