HTTP 標準 Content-Disposition 歷史上僅支援 ASCII,導致中文檔名在不同瀏覽器顯示不一。RFC 5987 定義了 filename* 參數支援 UTF-8,現代瀏覽器皆支援。本文提供相容所有主流瀏覽器的最佳實踐。
<?php
function sendFileDownload($filePath, $fileName = '')
{
if (!file_exists($filePath) || !is_readable($filePath)) {
http_response_code(404);
die('檔案不存在');
}
$fileName = $fileName ?: basename($filePath);
$fileSize = filesize($filePath);
$mimeType = mime_content_type($filePath) ?: 'application/octet-stream';
// 1. 基本 Header
header('Content-Type: ' . $mimeType);
header('Content-Length: ' . $fileSize);
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
header('Cache-Control: private, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// 2. 處理檔名編碼
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
// RFC 5987 標準格式:filename*=UTF-8''encoded_filename
$encodedName = rawurlencode($fileName);
$encodedName = str_replace('+', '%20', $encodedName); // 修正空格編碼
$disposition = "attachment; filename*=UTF-8''{$encodedName}";
// 3. 針對舊版 IE/Edge (Legacy) 提供 fallback
if (preg_match('/MSIE|Trident|Edge\/[0-9]{1,2}/', $ua)) {
// 老 IE 不支援 filename*,使用 filename 參數,需依瀏覽器編碼
// IE/Edge Legacy 期望 UTF-8 URL 編碼
$disposition = "attachment; filename=\"{$encodedName}\"";
}
// 4. Safari 舊版相容(可選)
// if (preg_match('/Safari\/[0-9]/', $ua) && !preg_match('/Chrome/', $ua)) { ... }
header('Content-Disposition: ' . $disposition);
// 5. 輸出檔案
readfile($filePath);
exit;
}
// 使用範例
$file = '/var/www/files/年度報表_2024.xlsx';
sendFileDownload($file, '年度報表_2024.xlsx');
?>
| 瀏覽器 | 版本 | filename* (RFC 5987) | filename (URL編碼) | 結果 |
|---|---|---|---|---|
| Chrome | 60+ | ✓ | ✓ | 正常 |
| Firefox | 50+ | ✓ | ✓ | 正常 |
| Edge | 79+ (Chromium) | ✓ | ✓ | 正常 |
| Edge Legacy | <= 44 | ✗ | ✓ (UTF-8) | 正常 |
| IE | 11 | ✗ | ✓ (UTF-8) | 正常 |
| Safari | 13+ | ✓ | ✓ | 正常 |
| Safari | < 13 | ✗ | ✓ (UTF-8) | 正常 |
function sendFileWithRange($filePath, $fileName = '')
{
$fileSize = filesize($filePath);
$rangeHeader = $_SERVER['HTTP_RANGE'] ?? '';
header('Accept-Ranges: bytes');
header('Content-Length: ' . $fileSize);
if ($rangeHeader) {
// 解析 Range: bytes=start-end
preg_match('/bytes=(\d+)-(\d*)/', $rangeHeader, $matches);
$start = (int)$matches[1];
$end = isset($matches[2]) && $matches[2] ? (int)$matches[2] : $fileSize - 1;
$end = min($end, $fileSize - 1);
$length = $end - $start + 1;
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $start . '-' . $end . '/' . $fileSize);
header('Content-Length: ' . $length);
$fp = fopen($filePath, 'rb');
fseek($fp, $start);
echo fread($fp, $length);
fclose($fp);
} else {
// 完整傳輸
sendFileDownload($filePath, $fileName);
}
exit;
}
採用 filename*=UTF-8''encoded 作為標準,搭配 User-Agent 判斷為舊版 IE/Edge 提供 filename="urlencoded" fallback,即可完美解決跨瀏覽器中文檔名下載亂碼問題。