如何通过PHP脚本下载大文件
使用PHP,我正在尝试提供由于授权问题而不在Web可访问目录中的大文件(最多200MB)。目前,我使用调用和一些标头来提供文件,但似乎PHP在发送之前将其加载到内存中。我打算在共享主机服务器上部署,这不允许我使用太多内存或添加自己的Apache模块,例如X-Sendfile。readfile()
出于安全原因,我不能让我的文件位于 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);