php readfile下载大文件失败的解决方法

时间:2021-10-14 00:34:28

本文实例讲述了php readfile下载大文件失败的解决方法。分享给大家供大家参考,具体如下:

大文件有200多M,只下载了200K就提示下载完成,且不报错。

原因是PHP内存有限制,需要改为按块下载,就是把大文件切块后逐块下载

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if (file_exists($file))
{
  if (FALSE!== ($handler = fopen($file, 'r')))
  {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: chunked'); //changed to chunked
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    //header('Content-Length: ' . filesize($file)); //Remove
    //Send the content in chunks
    while(false !== ($chunk = fread($handler,4096)))
    {
      echo $chunk;
    }
  }
  exit;
}
echo "<h1>Content error</h1><p>The file does not exist!</p>";

希望本文所述对大家PHP程序设计有所帮助。