0

以下脚本是我用来强制下载的。

// grab the requested file's name
$file_name = $_GET['file'];

// make sure it's a file before doing anything!
if(is_file($file_name)) {

    /*
        Do any processing you'd like here:
        1.  Increment a counter
        2.  Do something with the DB
        3.  Check user permissions
        4.  Anything you want!
    */

    // required for IE
    if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }

    // get the file mime type using the file extension
    switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
        case 'pdf': $mime = 'application/pdf'; break;
        case 'zip': $mime = 'application/zip'; break;
        case 'jpeg':
        case 'jpg': $mime = 'image/jpg'; break;
        default: $mime = 'application/force-download';
    }
    header('Pragma: public');   // required
    header('Expires: 0');       // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
    header('Cache-Control: private',false);
    header('Content-Type: '.$mime);
    header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: '.filesize($file_name));    // provide file size
    header('Connection: close');
    readfile($file_name);       // push it out
    exit();

} 

问题是上面的代码适用于小于100MB的文件,它不能适用于例如超过 200MB 的文件并说下载了 177 个字节。

我怎样才能摆脱这个问题?

编辑1:

主要脚本是从这里复制的。

谢谢!

4

1 回答 1

2

我怀疑您通过一次性将文件加载到内存中导致 PHP 使用过多内存 - 查看下载文件的内容,您可能会看到它是纯文本并包含 PHP 致命错误消息。

您最好以较小的块加载文件并将其传递回网络服务器以提供服务,例如,尝试使用以下内容替换您的“readfile”行:

// Open the file for reading and in binary mode
$handle = fopen($file_name,'rb');
$buffer = '';

// Read 1MB of data at a time, passing it to the output buffer and flushing after each 1MB
while(!feof($handle))
{
  $buffer = fread($handle, 1048576);
  echo $buffer;
  @ob_flush();
  @flush();
}
fclose($handle);
于 2013-08-06T12:18:06.047 回答