8 * 1024 bytes?這似乎是非常合理的,如果是這樣的話,你的高磁盤I/O可能與併發請求有關。您是否考慮過實施某種帶寬限制?這裏是一個PHP的唯一實現我爲我的框架,phunction:
public static function Download($path, $speed = null, $multipart = false)
{
if (strncmp('cli', PHP_SAPI, 3) !== 0)
{
if (is_file($path) === true)
{
while (ob_get_level() > 0)
{
ob_end_clean();
}
$file = @fopen($path, 'rb');
$size = sprintf('%u', filesize($path));
$speed = (empty($speed) === true) ? 1024 : floatval($speed);
if (is_resource($file) === true)
{
set_time_limit(0);
session_write_close();
if ($multipart === true)
{
$range = array(0, $size - 1);
if (array_key_exists('HTTP_RANGE', $_SERVER) === true)
{
$range = array_map('intval', explode('-', preg_replace('~.*=([^,]*).*~', '$1', $_SERVER['HTTP_RANGE'])));
if (empty($range[1]) === true)
{
$range[1] = $size - 1;
}
foreach ($range as $key => $value)
{
$range[$key] = max(0, min($value, $size - 1));
}
if (($range[0] > 0) || ($range[1] < ($size - 1)))
{
ph()->HTTP->Code(206, 'Partial Content');
}
}
header('Accept-Ranges: bytes');
header('Content-Range: bytes ' . sprintf('%u-%u/%u', $range[0], $range[1], $size));
}
else
{
$range = array(0, $size - 1);
}
header('Pragma: public');
header('Cache-Control: public, no-cache');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . sprintf('%u', $range[1] - $range[0] + 1));
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Content-Transfer-Encoding: binary');
if ($range[0] > 0)
{
fseek($file, $range[0]);
}
while ((feof($file) !== true) && (connection_status() === CONNECTION_NORMAL))
{
ph()->HTTP->Flush(fread($file, round($speed * 1024)));
ph()->HTTP->Sleep(1);
}
fclose($file);
}
exit();
}
else
{
ph()->HTTP->Code(404, 'Not Found');
}
}
return false;
}
上述方法有一些輕微的依賴,並增加了一些不必要的功能,如多部分下載,但你應該能夠重用節流邏輯沒有問題。
// serve file at 4 MBps (max)
Download('/path/to/file.ext', 4 * 1024);
你甚至可以在默認情況下更加慷慨取決於你從sys_getloadavg()
第一指標得到避免強調你的CPU的值降低$speed
。
可能有多個併發文件流會話。您需要限制併發請求的最大數量。 – 2011-05-18 18:23:54
我明白了。這可能是一個問題。但是,它會不會在從磁盤讀取實際數據和讀取數據之間產生這麼大的差異? – Lifetalk 2011-05-18 18:39:10
在提示符下用'free'檢查內存使用情況。看看交換文件是否被擊中 – 2011-05-18 20:15:24