gpt4 book ai didi

php - 使用 PHP 发送文件时可恢复下载?

转载 作者:IT老高 更新时间:2023-10-28 11:50:58 27 4
gpt4 key购买 nike

我们正在使用 PHP 脚本来隧道文件下载,因为我们不想暴露可下载文件的绝对路径:

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

很遗憾,我们注意到最终用户无法恢复通过此脚本进行的下载。

有没有办法通过这种基于 PHP 的解决方案来支持可恢复下载?

最佳答案

您需要做的第一件事是在所有响应中发送 Accept-Ranges: bytes header ,告诉客户端您支持部分内容。然后,如果收到带有 Range: bytes=x-y header 的请求(xy 是数字),则解析客户端的范围请求,像往常一样打开文件,提前寻找 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);

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

有一个 description of partial content here我在 fread 的文档页面上找到了一些关于部分内容的信息.

关于php - 使用 PHP 发送文件时可恢复下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/157318/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com