header() 是 PHP 發送原始 HTTP 回應標頭的核心函數。它不輸出網頁內容,而是指示瀏覽器「如何處理這個回應」——如重導向、設定快取策略、宣告內容類型、返回錯誤狀態碼等。掌握 header() 是掌握 HTTP 協定在 PHP 中應用的關鍵。
header(string $header, bool $replace = true, int $http_response_code = 0): void
"Location: https://example.com"。true(預設)替換同類型先前標頭;false 允許發送多個同名標頭(如多個 Set-Cookie)。header("X-My-Header: value", true, 200)。任何實際輸出(HTML、空白行、echo、print、BOM、include 產生的輸出)發生前,必須完成所有 header() 呼叫。否則拋出 Cannot modify header information - headers already sent 警告且標頭不生效。
<?php
// ❌ 錯誤:前面有空白行或 HTML
header("Location: https://example.com");
// ✅ 正確:檔案最開頭,無任何輸出
header("Location: https://example.com");
exit; // 重導向後務必 exit,防止後續代碼執行
?>
<?php
// 301 永久移動(SEO 傳遞權重)
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://new-domain.com/path");
exit;
// 302 Found / 303 See Other(預設行為,POST 會變 GET)
header("Location: https://example.com/login"); // 隱含 302
exit;
// 307 Temporary Redirect(保持原請求方法,如 POST 仍為 POST)
header("HTTP/1.1 307 Temporary Redirect");
header("Location: https://api.example.com/endpoint");
exit;
?>
注意:HTTP/1.1 規範要求 Location 值為絕對 URI。可用 $_SERVER['HTTP_HOST']、$_SERVER['REQUEST_URI'] 動態組裝。
<?php
// 404 Not Found - 告訴瀏覽器/搜尋引擎頁面不存在
header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found"); // 兼容舊版 CGI
// 此處可 include 自定義 404 頁面模板
include __DIR__ . '/templates/404.php';
exit;
// 403 Forbidden - 權限不足
header("HTTP/1.1 403 Forbidden");
exit("存取被拒絕");
// 500 Internal Server Error - 伺服器內部錯誤
header("HTTP/1.1 500 Internal Server Error");
exit("系統暫時無法服務,請稍後再試");
?>
<?php
// 現代瀏覽器 (HTTP/1.1)
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false); // 兼容舊寫法
// 舊版瀏覽器 / 代理伺服器 (HTTP/1.0)
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // 過去時間
header("Pragma: no-cache"); // HTTP/1.0 快取控制
// 最後修改時間(配合 ETag 可實現條件請求 304 Not Modified)
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
?>
<?php
$filePath = '/var/www/files/report.pdf';
$fileName = '2024_Q3_Report.pdf';
if (!is_file($filePath)) {
header("HTTP/1.1 404 Not Found");
exit("檔案不存在");
}
header("Content-Type: application/pdf"); // 或 application/octet-stream 通用二進位
header("Content-Disposition: attachment; filename=\"$fileName\""); // 關鍵:attachment 觸發下載
header("Content-Length: " . filesize($filePath)); // 讓瀏覽器顯示進度條
header("Accept-Ranges: bytes"); // 支援斷點續傳
header("Cache-Control: private, must-revalidate"); // 私有快取,不經代理
readfile($filePath); // 高效輸出大檔,不佔用 PHP 記憶體
exit;
?>
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false); // 發送兩個 WWW-Authenticate
header('Set-Cookie: flavor=chocolate', false);
header('Set-Cookie: size=large', false); // 發送多個 Cookie
header("Content-Type: application/json; charset=utf-8"); // API 回傳 JSON
header("Content-Type: text/html; charset=utf-8"); // 網頁預設
header("Content-Type: image/webp"); // 圖片直輸
header("Access-Control-Allow-Origin: https://trusted-site.com"); // 或 * 允許所有
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Max-Age: 86400"); // 預檢請求快取 1 天
// 處理 OPTIONS 預檢請求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit(0);
}
| 分類 | 代碼 | 含義 | 典型用途 |
|---|---|---|---|
| 2xx 成功 | 200 | OK | 一般成功回應 |
| 201 | Created | 資源建立成功(POST 回傳) | |
| 204 | No Content | 成功但無內容回傳(DELETE) | |
| 3xx 重導向 | 301 | Moved Permanently | 永久搬家,SEO 傳遞權重 |
| 302 | Found | 暫時重導向(預設) | |
| 304 | Not Modified | 條件請求未修改,走快取 | |
| 307 | Temporary Redirect | 暫時重導向,保持方法 | |
| 4xx 客戶端錯誤 | 400 | Bad Request | 請求格式錯誤 |
| 401 | Unauthorized | 未認證/Token 失效 | |
| 403 | Forbidden | 認證了但無權限 | |
| 404 | Not Found | 資源不存在 | |
| 429 | Too Many Requests | 限流/頻率控制 | |
| 5xx 伺服器錯誤 | 500 | Internal Server Error | 程式異常 |
| 502 | Bad Gateway | 上游伺服器無回應 | |
| 503 | Service Unavailable | 維護中/過載 |
include 檔案輸出、錯誤訊息輸出。用 ob_start() 開啟輸出緩衝可緩解但治標不治本。Location 值為絕對 URL、無拼字錯誤、已呼叫 exit()。filename 需 urlencode() 或依 RFC 5987 格式 filename*=UTF-8''%E4%B8%AD%E6%96%87.pdf。session_start() 會發送 Cache-Control 標頭,若需自訂快取策略,請在 session_start() 後再 header() 覆蓋。header() 是 PHP 與 HTTP 協定溝通的橋樑。熟練掌握重導向、狀態碼、快取控制、檔案下載、CORS 等核心場景,並嚴守「輸出前呼叫」鐵律,能讓你的 Web 應用更專業、更符合標準、更利於 SEO 與使用者體驗。