7

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

以下是相关代码:

/* 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');

所以这一定是使用fopenand的问题fread

4

2 回答 2

0

Why don't you just do a HTTP header redirect to the binary file itself? That way you take the PHP out of the equation all together since all you want to do is serve up the file.

于 2013-02-02T15:57:58.570 回答
0

基本上,您正在使用 PHP 构建代理服务器。您是否考虑过使用 mod_proxy ( http://httpd.apache.org/docs/2.2/mod/mod_proxy.html ) 或 Squid Proxy ( http://www.squid-cache.org/ )

于 2013-02-02T23:05:06.650 回答