1.問題:
PHP在使用readfile函數(shù)定義下載文件時(shí)候,文件不可以過大,否則會下載失敗,文件損壞且不報(bào)錯(cuò);
2.原因:
這個(gè)是因?yàn)閞eadfile讀取文件的時(shí)候會把文件放入緩存,導(dǎo)致內(nèi)存溢出;
3.解決:分段下載,并限制下載速度;
<?php//設(shè)置文件最長執(zhí)行時(shí)間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'); // 設(shè)置指針位置 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服務(wù)器 flush(); // 刷新Web服務(wù)器緩沖區(qū)到瀏覽器 sleep(1); // 每1秒 下載 2 MB } // 關(guān)閉緩沖區(qū) ob_end_clean(); fclose($fp);} else { echo 'file not exists or has been removed!';}exit();總結(jié)
以上所述是小編給大家介紹的PHP下載大文件失敗并限制下載速度的實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對VeVb武林網(wǎng)網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
新聞熱點(diǎn)
疑難解答
圖片精選