文件下载在php,内存限制问题?

时间:2011-02-14 03:48:48

标签: php apache file memory limit

我的一个客户决定将网站从一个不错的服务器移动到...让我们称之为服务器不太好。

问题是,有一个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);
}

2 个答案:

答案 0 :(得分:3)

请改用readfile()。它将以小块的形式传输文件并处理所有后台工作,以尽量减少内存使用量。

答案 1 :(得分:0)

您确实想要fpassthru(),但是如果主机禁用了fopen(),他们也可能也禁用了fpassthru()。在这种情况下,您要么与房东协商,要么开始寻找更好的房东。否则您根本无法分发大文件。

在我看来,主机在故意削弱可用功能以降低带宽成本和/或CPU使用率。如果它们允许读取任何文件,则不应该涉及安全规则。