【发布时间】:2011-09-25 13:10:44
【问题描述】:
使用 PHP,我正在尝试提供由于授权问题而不在 Web 可访问目录中的大文件(最大可能为 200MB)。目前,我使用readfile() 调用以及一些标头来提供文件,但似乎 PHP 在发送之前将其加载到内存中。我打算部署在共享主机服务器上,这不会让我使用太多内存或添加我自己的 Apache 模块,例如 X-Sendfile。
出于安全原因,我不能让我的文件位于 Web 可访问目录中。有人知道我可以在共享托管服务器上部署的内存密集型方法吗?
编辑:
if(/* My authorization here */) {
$path = "/uploads/";
$name = $row[0]; //This is a MySQL reference with the filename
$fullname = $path . $name; //Create filename
$fd = fopen($fullname, "rb");
if ($fd) {
$fsize = filesize($fullname);
$path_parts = pathinfo($fullname);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
break;
case "zip":
header("Content-type: application/zip");
break;
default:
header("Content-type: application/octet-stream");
break;
}
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 1*(1024*1024));
echo $buffer;
ob_flush();
flush(); //These two flush commands seem to have helped with performance
}
}
else {
echo "Error opening file";
}
fclose($fd);
【问题讨论】:
-
不同意这是重复的,这家伙正试图通过 PHP 下载,而另一个问题是如何下载大文件.. 老实说不同的问题。