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

How Can I Implement Resumable Downloads in PHP File Tunneling?

Susan Sarandon
Susan SarandonOriginal
2024-12-08 19:52:11807browse

How Can I Implement Resumable Downloads in PHP File Tunneling?

Resumable Downloads with PHP File Tunneling

When using PHP to stream file downloads, it can be desirable to enable resumable downloads for users. However, the default PHP script setup often prevents downloads from being resumed.

To support resumable downloads with PHP, follow these steps:

  1. Send Accept-Ranges Header:
    Send the Accept-Ranges: bytes header in all responses to indicate that the server supports resuming downloads.
  2. Handle Range Requests:
    Inspect incoming requests for a Range: bytes=x-y header, where x is the offset and y is the end byte of the requested range.
  3. Seek File and Send Range:
    Open the file and seek to the specified offset. Then, send the requested byte range using fread().
  4. Set Partial Content Headers:
    For range requests, set the HTTP/1.0 206 Partial Content header and specify the content range using Content-Range: bytes x-y/filesize.

Implementing these steps should enable resumable downloads in your PHP file tunneling setup. Here's an example PHP code that demonstrates the process:

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

The above is the detailed content of How Can I Implement Resumable Downloads in PHP File Tunneling?. 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