PHP下载超大文件 解决文件只下载一半问题

/**
 * @param $filePath //下载文件的路径
 * @param int $readBuffer //分段下载 每次下载的字节数 默认4096bytes
 * @param array $allowExt //允许下载的文件类型
 * @return void
 */
function downloadFile($filePath, $readBuffer = 4096, $allowExt = ['jpeg', 'jpg', 'peg', 'gif', 'zip', 'rar', 'txt'])
{
  //设置文件最长执行时间
  set_time_limit(0);
   
  //检测下载文件是否存在 并且可读
  if (!is_file($filePath) && !is_readable($filePath)) {
      return false;
  }
  //检测文件类型是否允许下载
  $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  if (!in_array($ext, $allowExt)) {
      return false;
  }
   
  if (FALSE!== ($handler = fopen($filePath, 'rb')))
  {
    //设置指针位置  
    //fseek($handler, $range);
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($filePath));
    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($filePath)); //Remove

    //Send the content in chunks
    while (!feof($handler)) {  
        //设置文件最长执行时间
        echo fread($handler, $readBuffer); //输出文件  
        flush(); //输出缓冲  
        ob_flush();  
    }  
    fclose($handler);
    exit (); 
  }
  return false;
}

本人亲测!!!

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值