<?php
/**
* @param $filePath //下載文件的路徑
* @param int $readBuffer //分段下載 每次下載的字節數 默認1024bytes
* @param array $allowExt //允許下載的文件類型
* @return void
*/
function downloadFile($filePath, $readBuffer = 1024, $allowExt = ['jpeg', 'jpg', 'peg', 'gif', 'zip', 'rar', 'txt'])
{
//檢測下載文件是否存在 並且可讀
if (!is_file($filePath) && !is_readable($filePath)) {
return false;
}
//檢測文件類型是否允許下載
$ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
if (!in_array($ext, $allowExt)) {
return false;
}
//設置頭信息
//聲明瀏覽器輸出的是字節流
header('Content-Type: application/octet-stream');
//聲明瀏覽器返回大小是按字節進行計算
header('Accept-Ranges:bytes');
//告訴瀏覽器文件的總大小
$fileSize = filesize($filePath);//坑 filesize 如果超過2G 低版本php會返回負數
header('Content-Length:' . $fileSize); //注意是'Content-Length:' 非Accept-Length
//聲明下載文件的名稱
header('Content-Disposition:attachment;filename=' . basename($filePath));//聲明作為附件處理和下載后文件的名稱
//獲取文件內容
$handle = fopen($filePath, 'rb');//二進制文件用‘rb’模式讀取
while (!feof($handle) ) { //循環到文件末尾 規定每次讀取(向瀏覽器輸出為$readBuffer設置的字節數)
echo fread($handle, $readBuffer);
}
fclose($handle);//關閉文件句柄
exit;
}