首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Readfile issue PHP

Readfile issue PHP
EN

Stack Overflow用户
提问于 2012-07-12 23:42:35
回答 2查看 482关注 0票数 0

我正在尝试使用php头文件和readfile函数强制下载,以下是我的代码:

代码语言:javascript
复制
if(file_exists($file_url)){header('Content-Type: '.$ftype);
header('Content-Transfer-Encoding: binary');
header('Content-Transfer-Encoding: binary'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Pragma: public');
header("Content-Length: " . filesize($dir.$fname));
header("Content-disposition: attachment; filename=\"".$fname."\""); 
ob_clean(); 
flush(); 
readfile($dir.$fname);
exit;}

问题是大于37mb的文件以0字节下载。我已经检查了php的配置和memory_limit设置为200mb,我已经尝试下载块使用这个:

代码语言:javascript
复制
$filename = $dir.$fname;
$filesize = filesize($filename);

    $chunksize = 4096;
    if($filesize > $chunksize)
    {
        $srcStream = fopen($filename, 'rb');
        $dstStream = fopen('php://output', 'wb');

        $offset = 0;
        while(!feof($srcStream)) {
            $offset += stream_copy_to_stream($srcStream, $dstStream, $chunksize, $offset);
        }

        fclose($dstStream);
        fclose($srcStream);   
    }
    else 
    {
        // stream_copy_to_stream behaves() strange when filesize > chunksize.
        // Seems to never hit the EOF.
        // On the other handside file_get_contents() is not scalable. 
        // Therefore we only use file_get_contents() on small files.
        echo file_get_contents($filename);
    }

但它不是强制下载,而是显示文件。有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2012-07-13 00:07:17

代码语言:javascript
复制
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; 
}
header('Content-Type: '.$ftype);
header('Content-Transfer-Encoding: binary'); 
header('Expires: 0'); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Pragma: public');
header("Content-Length: " . filesize($dir.$fname));
header("Content-disposition: attachment; filename=\"".$fname."\""); 
readfile_chunked($filen);
票数 1
EN

Stack Overflow用户

发布于 2012-07-12 23:54:49

试试这个。

代码语言:javascript
复制
header ("Content-Disposition: attachment; filename=".$filename."\n\n");
header ("Content-Type: application/octet-stream");
@readfile($link); // Path to file
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11455534

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档