下载大文件不起作用

时间:2013-10-14 06:31:31

标签: php download

嘿,我有以下代码下载大文件,但下载确实每次都停止而没有完成下载

function download($file)
{
    include('logger.php5');
    $log = new Logging();
    $log->lfile('download.log');
    ini_set('max_execution_time', 86400);
    //header('Location: '.$file);
    $filesize = filesize($file);
    $filename = pathinfo($file, PATHINFO_BASENAME);
    $filext = pathinfo($file, PATHINFO_EXTENSION);
    $mime = include('mime.php5');

    $log->lwrite(ini_get('max_execution_time'));
    $log->lwrite(sprintf('%s %s %s %s', $filename, $filext, $mime[$filext], human_filesize($filesize)));
    $log->lclose();
    @ob_end_clean();
    session_write_close();
    header("Content-Description: File Transfer");
    header("Content-Type: ".$mime[$filext]);
    header("Content-Disposition: ".
     (!strpos($HTTP_USER_AGENT,"MSIE 5.5")?"attachment; ":"").
     "filename=".$filename);
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$filesize);
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header('Pragma: public');
    header('Expires: 0');
    $done = readfile_chunked($file);
}

function readfile_chunked($filename,$retbytes=true) { 
   $chunksize = 1*(1024*1024); // how many bytes per chunk 
   $buffer = ''; 
   $cnt =0; 
   // $handle = fopen($filename, 'rb'); 
   $handle = fopen($filename, 'rb'); 
   if ($handle === false) { 
       return false; 
   } 
   while (!feof($handle)) { 
       $buffer = fread($handle, $chunksize); 
       echo $buffer; 
       ob_flush(); 
       flush(); 
       if ($retbytes) { 
           $cnt += strlen($buffer); 
       } 
   } 
       $status = fclose($handle); 
   if ($retbytes && $status) { 
       return $cnt; // return num. bytes delivered like readfile() does. 
   } 
   return $status;
} 

每次调用脚本时,下载启动但在400MB后停止,文件本身大小为778MB。

有人可以看到代码有问题吗?

更新

在尝试记录readfile_chunked的返回值之后,感觉就像脚本被停止而不是下载本身。因为我无法在readfile_chunked电话后获得日志条目。

1 个答案:

答案 0 :(得分:-1)

PHP中的filesize函数可能存在问题。有大文件大小读取的已知错误,当​​您将文件作为标题发送时,我建议您在不使用此行的情况下尝试脚本:

 header("Content-Length: ".$filesize);

哦,也许你可以看看这一行:

header("Content-Transfer-Encoding: binary");

我认为应该检查每个文件的编码。像这样:

$finfo = finfo_open(FILEINFO_MIME);

//check to see if the mime-type starts with 'text'
return substr(finfo_file($finfo, $filename), 0, 4) == 'text';

如果是文本文件,则应使用ASCII ofcourse。与问题无关,但我认为这是对你的脚本有用的补充:)