1.問題: PHP在使用readfile函數定義下載文件時候,文件不可以過大,否則會下載失敗,文件損壞且不報錯;
2.原因: 這個是因為readfile讀取文件的時候會把文件放入緩存,導致內存溢出;
3.解決:分段下載,並限制下載速度;
-
-
//設置文件最長執行時間
-
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);
-
-
// 開啟緩沖區
-
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);
-
} else {
-
echo 'file not exists or has been removed!';
-
}
-
-
exit();復制代碼
轉載於:https://juejin.im/post/5cd445866fb9a031f10ca672