/** * @param $filePath //下載文件的路徑 * @param int $readBuffer //分段下載 每次下載的字節數 默認1024bytes * @param array $allowExt //允許下載的文件類型 * @return void */ public function downloadFile($filePath, $readBuffer = 1024, $allowExt = ['jpeg', 'jpg', 'peg', 'gif', 'zip', 'rar', 'txt', 'xls', 'xlsx']) { //檢測下載文件是否存在 並且可讀 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; }
PHP 分段下載 服務器文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.