使用PHP发送文件时可以断点续传吗?

2024-04-16

我们使用 PHP 脚本进行隧道文件下载,因为我们不想公开可下载文件的绝对路径:

header("Content-Type: $ctype");
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=\"$fileName\"");
readfile($file);

不幸的是,我们注意到最终用户无法恢复通过此脚本传递的下载。

有什么办法可以使用这种基于 PHP 的解决方案来支持断点续传下载吗?


您需要做的第一件事就是发送Accept-Ranges: bytes所有响应中的标头,以告诉客户端您支持部分内容。然后,如果请求带有Range: bytes=x-y收到标头(带有x and y是数字)您解析客户端请求的范围,照常打开文件,查找x提前字节并发送下一个y - x字节。还将响应设置为HTTP/1.0 206 Partial Content.

在没有测试过任何东西的情况下,这或多或少是可行的:

$filesize = filesize($file);

$offset = 0;
$length = $filesize;

if ( isset($_SERVER['HTTP_RANGE']) ) {
    // if the HTTP_RANGE header is set we're dealing with partial content

    $partialContent = true;

    // find the requested range
    // this might be too simplistic, apparently the client can request
    // multiple ranges, which can become pretty complex, so ignore it for now
    preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);

    $offset = intval($matches[1]);
    $length = intval($matches[2]) - $offset;
} else {
    $partialContent = false;
}

$file = fopen($file, 'r');

// seek to the requested offset, this is 0 if it's not a partial content request
fseek($file, $offset);

$data = fread($file, $length);

fclose($file);

if ( $partialContent ) {
    // output the right headers for partial content

    header('HTTP/1.1 206 Partial Content');

    header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $filesize);
}

// output the regular HTTP headers
header('Content-Type: ' . $ctype);
header('Content-Length: ' . $filesize);
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Accept-Ranges: bytes');

// don't forget to send the data too
print($data);

我可能错过了一些明显的东西,而且我肯定忽略了一些潜在的错误来源,但这应该是一个开始。

有一个此处描述部分内容 http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt我在文档页面上找到了有关部分内容的一些信息fread http://se.php.net/manual/en/function.fread.php.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用PHP发送文件时可以断点续传吗? 的相关文章

随机推荐