在 PHP 開發中,header() 函數不僅能發送原始 HTTP 報頭,更是實現文件下載功能的關鍵工具。本文將系統梳理其核心應用場景,並提供可直接落地的代碼範例。
header() 最常見的用途是頁面跳轉與狀態碼輸出:
<?php
// 多次調用以最後一次為準(需無輸出內容)
header('Location: https://www.example.com');
exit(); // 最佳實踐:跳轉後立即終止腳本
?>
注意:若跳轉前有 echo 輸出,第二個 header 將生效(如輸出後跳轉至 Google)。
<?php
// 401 未授權
header('HTTP/1.1 401 Unauthorized');
header('Status: 401 Unauthorized');
// 404 頁面不存在(偽裝頁面不存在)
header('HTTP/1.1 404 Not Found');
header('Status: 404 Not Found');
?>
通過設置 Content-Type 與 Content-Disposition 實現強制下載:
<?php
$filename = '/path/to/real_file.pdf'; // 服務器絕對路徑
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="download_name.pdf"');
readfile($filename);
exit();
?>
<?php
$file = 'server_file.rar';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="download_name.rar"');
readfile($file);
exit();
?>
正確的 MIME 類型能提升瀏覽器識別準確性:
| 副檔名 | MIME 類型 |
|---|---|
| application/pdf | |
| .doc | application/msword |
| .docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
| .xls | application/vnd.ms-excel |
| .xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
| .zip | application/x-zip-compressed |
| .rar | application/octet-stream |
| .jpg/.jpeg | image/jpeg |
| .png | image/png |
| .mp3 | audio/mpeg |
| .mp4 | video/mp4 |
| .txt | text/plain |
| .html | text/html |
| .js | text/javascript |
| .css | text/css |
fread() 分塊讀取,避免記憶體溢出urlencode($filename) 或使用 RFC 5987 格式header('Cache-Control: no-cache, must-revalidate') 防止緩存干擾ob_clean() 清除前序輸出,確保文件純淨<?php
function downloadFile($filePath, $downloadName = '', $mimeType = '') {
if (!is_file($filePath)) {
header('HTTP/1.1 404 Not Found');
exit('文件不存在');
}
$downloadName ?: $downloadName = basename($filePath);
$mimeType ?: $mimeType = mime_content_type($filePath) ?: 'application/octet-stream';
// 清除輸出緩衝
if (ob_get_level()) ob_clean();
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="' . rawurlencode($downloadName) . '"');
header('Content-Length: ' . filesize($filePath));
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
readfile($filePath);
exit();
}
?>