我正在编写一个脚本,它将通过我的服务器将文件从网址流式传输给用户。在当前状态下,它可以工作,但速度很慢。
以下是相关代码:
/* 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/s。
我知道这不是限制传输速度的脚本,因为我将它设置为 1MB/s。我也想不出这个脚本中的任何东西会产生很大的开销,从而降低速度。
编辑:有趣的事情,如果我这样做,readfile()
我几乎可以得到完整的下载速度:
readfile('http://cachefly.cachefly.net/100mb.test');
所以这一定是使用fopen
and的问题fread
?