因為PHP處理文件下載readfile是寫入PHP 緩沖區的,readfile會把文件內容直接讀到緩沖區,如果下一個大文件,那么緩沖區就會爆掉!大文件不要用readfile,否則瀏覽器端就會報錯。
處理如下
set_time_limit(0);
$filesize = filesize($file);
header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . $filesize); header('Content-Disposition: attachment; filename=' . $file_name); // 打開文件 $fp = fopen($file, 'rb'); // 設置指針位置 fseek($fp, 0); // 開啟緩沖區 //ob_start(); // 分段讀取文件 while (!feof($fp)) { $chunk_size = 1024 * 1024 * 2; // 2MB echo fread($fp, $chunk_size); ob_flush(); // 刷新PHP緩沖區到Web服務器 flush(); // 刷新Web服務器緩沖區到瀏覽器 // sleep(1); // 每1秒 下載 2 MB } // 關閉緩沖區 //ob_end_clean(); fclose($fp);
關於PHP大文件切片上傳,詳見項目:https://gitee.com/FCesky/big-file-uploader