header() 必須在任何輸出之前呼叫 (包括空白、BOM、echo、HTML)。否則觸發
Cannot modify header information - headers already sent警告並失效。
| Header | 用途 | 範例 |
|---|---|---|
Content-Type | 回應內容 MIME 類型 | header('Content-Type: application/json'); |
Location | 重導向 | header('Location: https://example.com'); |
Status | HTTP 狀態碼 | header('Status: 404 Not Found'); |
新版多重 MIME (Multipart) 可出現多次 Content-Type。
header("Location: https://www.php.net");
exit; // 重要:停止後續執行
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // 過去時間
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache"); // HTTP/1.0 相容
header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found");
// 可選:輸出自訂 404 頁面內容
include '404.html';
exit;
$file = '/path/to/file.pdf';
$filename = 'download.pdf';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile($file); // 高效輸出檔案內容
exit;
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status'=>'ok', 'data'=>$data]);
exit;
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($imgPath));
readfile($imgPath);
RFC 7231 允許相對路徑,但建議用絕對 URL 避免相容性問題。
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://new.example.com/");
// SEO 權重傳遞、瀏覽器/搜尋引擎更新書籤/索引
header("HTTP/1.1 302 Found"); // 預設
header("Location: /temp-page");
// 內嵌顯示 (瀏覽器嘗試直接開啟)
header('Content-Disposition: inline; filename="report.pdf"');
// 附件下載 (強制另存)
header('Content-Disposition: attachment; filename="report.pdf"');
// RFC 5987 編碼中文檔名
$encoded = rawurlencode($filename);
header("Content-Disposition: attachment; filename*=UTF-8''{$encoded}");
前有空白/換行include/require 的檔案尾部有關閉標籤 ?> 後的空白 → 純 PHP 檔案省略結束標籤display_errors=Off 或 error_reporting(0)session.cache_limiter = '' 或手動 session_start() 在最頂端if (headers_sent($file, $line)) {
error_log("Headers already sent in $file:$line");
} else {
header("Location: /login");
}
headers_list():已發送/待發送 Header 列表header_remove():移除已設定但未發送的 Headerhttp_response_code():設定/取得狀態碼 (PHP 5.4+)