0514-86177077
9:00-17:00(工作日)
1.問題:
PHP在使用readfile函數(shù)定義下載文件時候,文件不可以過大,否則會下載失敗,文件損壞且不報錯;
2.原因:
這個是因為readfile讀取文件的時候會把文件放入緩存,導致內(nèi)存溢出;
3.解決:分段下載,并限制下載速度;
?php //設置文件最長執(zhí)行時間 set_time_limit(0); if (isset($_GET['filename']) !empty($_GET['filename'])) { $file_name = $_GET['filename']; $file = __DIR__ . '/assets/' . $file_name; } else { echo 'what are your searching for?'; exit(); } if (file_exists($file) is_file($file)) { $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); // 開啟緩沖區(qū) ob_start(); // 分段讀取文件 while (!feof($fp)) { $chunk_size = 1024 * 1024 * 2; // 2MB echo fread($fp, $chunk_size); ob_flush(); // 刷新PHP緩沖區(qū)到Web服務器 flush(); // 刷新Web服務器緩沖區(qū)到瀏覽器 sleep(1); // 每1秒 下載 2 MB } // 關閉緩沖區(qū) ob_end_clean(); fclose($fp); } else { echo 'file not exists or has been removed!'; } exit();
總結
以上所述是小編給大家介紹的PHP下載大文件失敗并限制下載速度的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持! 如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
標簽:重慶 巴彥淖爾 衡陽 鷹潭 十堰 臨沂 麗江 銅陵
上一篇:PHP 7.4 新語法之箭頭函數(shù)實例詳解
下一篇:Laravel推薦使用的十個輔助函數(shù)
Copyright ? 1999-2012 誠信 合法 規(guī)范的巨人網(wǎng)絡通訊始建于2005年
蘇ICP備15040257號-8