文件在php下载,内存限制问题?
我的一个客户决定将网站从一个不错的服务器移动到...让我们称之为更好的服务器。
问题是,有一个40MB的文件需要下载,而服务器上的内存限制是32个。为了让我更加困难,他们不允许fopen ...
此外,如果我减小文件大小为20MB它工作正常。
所以,我的问题是,除了缩小文件大小外,我还能做些什么?
谢谢
编辑:`
$fsize = filesize($file_path);
$path_parts = pathinfo($file_path);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf": $ctype = "application/pdf";
break;
case "exe": $ctype = "application/octet-stream";
break;
case "zip": $ctype = "application/zip";
break;
case "doc": $ctype = "application/msword";
break;
case "xls": $ctype = "application/vnd.ms-excel";
break;
case "ppt": $ctype = "application/vnd.ms-powerpoint";
break;
case "gif": $ctype = "image/gif";
break;
case "png": $ctype = "image/png";
break;
case "jpeg":
case "jpg": $ctype = "image/jpg";
break;
default: $ctype = "application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename="" . basename($file_path) . "";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);
ob_clean();
flush();
readfile($file_path);`
我在php.net上看到的代码
// If it's a large file, readfile might not be able to do it in one go, so:
$chunksize = 1 * (1024 * 1024); // how many bytes per chunk
if ($size > $chunksize) {
$handle = fopen($realpath, 'rb');
$buffer = '';
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
echo $buffer;
ob_flush();
flush();
}
fclose($handle);
} else {
readfile($realpath);
}
使用readfile()
代替。 它将以小块形式传输文件,并处理所有后台工作,以最大限度地减少内存使用量。