我正在编写一个脚本,它会通过我的服务器将一个文件从一个网址流式传输到用户。在当前状态下它可以工作,但速度非常慢。
相关代码如下:
/* Bytes per second */
define('TRANSFER_CAP', 1048576);
/* Hard part... stream the file to the user */
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . $filename);
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $filesize);
$file = fopen($fileLocation, 'rb');
if(!$file) {
// TODO: handle errors
}
while(!feof($file)) {
echo fread($file, TRANSFER_CAP / 2);
ob_flush();
flush();
/* Limit the download speed by sleeping */
usleep(500);
}
这个脚本在我的本地机器上运行。当我在浏览器中请求文件时(不通过脚本),我获得了大约 2.5MB/s 的稳定下载速度,这是我的互联网最大速度。但是,如果我运行脚本并尝试下载相同的文件,我只能获得大约 240-250KB/秒的速度。
我知道这不是限制传输速度的脚本,因为我将它设置为 1MB/s。我也想不出此脚本中会产生大量开销从而降低速度的任何内容。
编辑:有趣的是,如果我改为使用 readfile()
执行此操作,我几乎可以达到我的全部下载速度:
readfile('http://cachefly.cachefly.net/100mb.test');
所以使用 fopen
和 fread
一定有问题吗?
最佳答案
为什么不直接将 HTTP header 重定向到二进制文件本身呢?这样一来,您就可以将 PHP 完全排除在外,因为您要做的就是提供文件。
关于php - 通过 PHP 从 Internet 流式传输文件很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14638357/