通过PHP从Internet流式传输文件很慢

Jam*_*son 7 php download stream

我正在编写一个脚本,它将文件从网址通过我的服务器流式传输给用户.在目前的状态下它可以工作,但速度非常慢.

这是相关的代码:

/* 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);
}
Run Code Online (Sandbox Code Playgroud)

此脚本在我的本地计算机上运行.当我在浏览器中请求文件(不通过脚本)时,我获得了大约2.5MB/s的可靠下载速度,这是我的互联网最大速度.但是,如果我运行脚本并尝试下载相同的文件,我只能得到大约240-250KB/s.

我知道这不是限制传输速度的脚本,因为我将它设置为1MB/s.我也想不出这个脚本会产生很大的开销,这会降低速度.

编辑:有趣的事情,如果我这样做,readfile()我得到几乎我的完整下载速度:

readfile('http://cachefly.cachefly.net/100mb.test');
Run Code Online (Sandbox Code Playgroud)

所以它必须是使用fopen和的问题fread

小智 0

为什么不直接将 HTTP 标头重定向到二进制文件本身呢?这样,您就可以将 PHP 排除在外,因为您要做的就是提供文件。