預設情況下,瀏覽器會嘗試在頁面內預覽圖片、PDF、影音等檔案。若需強制觸發「另存新檔」對話框,必須發送正確的 HTTP Header。本文整理跨瀏覽器相容的最佳 Header 組合,並解決常見坑點。
<?php
function forceDownload(string $filePath, string $fileName = ''): void {
if (!is_file($filePath) || !is_readable($filePath)) {
http_response_code(404);
exit('檔案不存在或不可讀');
}
$fileName = $fileName ?: basename($filePath);
$mimeType = mime_content_type($filePath) ?: 'application/octet-stream';
$fileSize = filesize($filePath);
// 必要 Header
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"; filename*=UTF-8\'\'' . rawurlencode($fileName));
header('Content-Length: ' . $fileSize);
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
// 快取控制(視需求調整)
header('Cache-Control: private, must-revalidate');
header('Pragma: private');
header('Expires: 0');
// 輸出檔案
readfile($filePath);
exit;
}
| Header | 作用 | 注意事項 |
|---|---|---|
| Content-Disposition | 指示瀏覽器下載而非顯示 | 雙重 filename 編碼相容 RFC 5987 與舊版瀏覽器 |
| Content-Length | 告知檔案大小,啟用進度條 | 大檔案需確保 PHP 整數不溢位(64-bit 環境無憂) |
| Content-Transfer-Encoding: binary | 避免傳輸層編碼修改二進位資料 | 對應 HTTP/1.1 標準 |
| Accept-Ranges: bytes | 支援斷點續傳、多執行緒下載 | 需搭配 Range 請求處理(見下文) |
| Cache-Control: private | 允許瀏覽器快取但禁止代理快取 | 敏感檔案改用 no-store |
readfile() 會將整個檔案讀入記憶體,大檔案易造成 OOM。正確做法:
function sendFileChunked(string $path, int $start = 0, int $end = null): void {
$handle = fopen($path, 'rb');
fseek($handle, $start);
$buffer = 1024 * 8; // 8KB
while (!feof($handle) && ($end === null || ftell($handle) <= $end)) {
echo fread($handle, $buffer);
@ob_flush(); @flush();
}
fclose($handle);
}
// 在 forceDownload 中加入 Range 處理
if (isset($_SERVER['HTTP_RANGE'])) {
// 解析 Range header,發送 206 Partial Content
// 實作略,參考 RFC 7233
}
filename*=UTF-8''... 格式,舊版 IE 需額外 filename="..." 雙重寫入。?> 前無空白、關閉 output_buffering 或手動 ob_clean()。fastcgi_buffers、fastcgi_max_temp_file_size,或啟用 X-Accel-Redirect 讓 Nginx 直接傳檔。Cache-Control: no-store,改用 private。高流量站點應將檔案傳輸卸載給 Web Server:
// PHP 僅驗證權限,發送內部導向 Header
header('X-Accel-Redirect: /protected-files/' . $internalPath);
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
exit;
// Nginx 設定:location /protected-files { internal; alias /var/www/files/; }
此方式零 PHP 記憶體佔用、支援 sendfile 系統呼叫、可處理 TB 級大檔。
正確的 Header 組合是強制下載的基礎,但生產環境更應關注大檔案傳輸效能與安全性。採用 X-Accel-Redirect 架構分離權限驗證與檔案傳輸,是企業級應用的標準做法。