【发布时间】:2011-09-05 22:28:33
【问题描述】:
我正在尝试向用户提供大型 zip 文件。当有 2 个并发连接时,服务器会耗尽内存 (RAM)。我将内存量从 300MB 增加到 4GB(Dreamhost VPS),然后它运行良好。
我需要允许超过 2 个并发连接。实际的 4GB 将允许 20 个并发连接(太糟糕了)。
嗯,我正在使用的当前代码需要双倍内存,然后是实际文件大小。这太糟糕了。我想要将文件“流式传输”给用户之类的东西。所以我会分配不超过提供给用户的块。
以下代码是我在 CodeIgniter(PHP 框架)中使用的代码:
ini_set('memory_limit', '300M'); // it was the maximum amount of memory from my server
set_time_limit(0); // to avoid the connection being terminated by the server when serving bad connection downloads
force_download("download.zip", file_get_contents("../downloads/big_file_80M.zip"));exit;
force_download函数如下(CodeIgniter默认辅助函数):
function force_download($filename = '', $data = '')
{
if ($filename == '' OR $data == '')
{
return FALSE;
}
// Try to determine if the filename includes a file extension.
// We need it in order to set the MIME type
if (FALSE === strpos($filename, '.'))
{
return FALSE;
}
// Grab the file extension
$x = explode('.', $filename);
$extension = end($x);
// Load the mime types
@include(APPPATH.'config/mimes'.EXT);
// Set a default mime if we can't find it
if ( ! isset($mimes[$extension]))
{
$mime = 'application/octet-stream';
}
else
{
$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
}
// Generate the server headers
if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE)
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".strlen($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
}
exit($data);
}
我尝试了一些在 Google 中找到的基于块的代码,但文件交付时总是损坏。可能是因为代码不好。
谁能帮帮我?
【问题讨论】:
-
您是否尝试过使用标头
Location重定向到文件? -
在我看来,您最好只为用户提供指向文件的直接链接...
-
我忘记告诉您文件位于无法通过网络访问的文件夹中。这是出于安全原因。如果用户通过身份验证过程,我只会提供文件。我会尝试以下建议,并会回来投票选出最佳答案。
-
感谢文字修改,@p.campbell 我想我昨晚太累了... :)
标签: php apache codeigniter memory-management force-download