Cache-Control: no-cache、Pragma: no-cache 的 HTTPS 下載響應會拒絕保存。filename*=UTF-8''...)早期版本。header("Pragma: "); // 清除 Pragma
header("Cache-Control: "); // 清除 Cache-Control
header("Content-Type: $type"); // 具體 MIME 類型
header("Accept-Ranges: bytes");
header("Content-Transfer-Encoding: base64");
header("Accept-Length: " . filesize($path));
header("Content-Disposition: attachment; filename=" . urlencode($filename)); // 關鍵:urlencode
readfile($path);
exit;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream'); // 強制下載
header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); // IE 需要這些
header('Pragma: public'); // IE 需要 public
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
| 問題 | 關鍵 Header | 說明 |
|---|---|---|
| IE 提示無法訪問 | Cache-Control: must-revalidate, post-check=0, pre-check=0 Pragma: public | 替換 no-cache/no-store,允許 IE 緩存到臨時文件夾再下載 |
| 中文文件名亂碼 | Content-Disposition: attachment; filename=urlencode($name) | IE 不支持 RFC 5987 格式,必須 urlencode |
| HTTPS 下載失敗 | 清除 Pragma/Cache-Control no-cache | IE 禁止缓存 HTTPS 響應到磁盤 |
| 大文件記憶體溢出 | readfile() / fread() 循環 | readfile 內部流式輸出不佔用 PHP 內存 |
function downloadFile($filePath, $fileName = null, $mimeType = 'application/octet-stream') {
if (!is_file($filePath)) { http_response_code(404); exit('File not found'); }
$fileName = $fileName ?: basename($filePath);
$fileSize = filesize($filePath);
// 兼容 RFC 5987 (現代瀏覽器) + urlencode (舊IE)
$encodedName = rawurlencode($fileName);
$disposition = "attachment; filename=\"$encodedName\"; filename*=UTF-8''$encodedName";
header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: ' . $disposition);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $fileSize);
// 關閉輸出緩衝,避免內存峰值
if (ob_get_level()) ob_end_clean();
readfile($filePath);
exit;
}