在 PHP 開發中,header() 函數是實現頁面跳轉、設定 HTTP 標頭、控制快取等核心操作的關鍵工具。然而,許多開發者常遇到「重定向不生效」或跳出 Warning: Cannot modify header information - headers already sent 的錯誤。本文將系統梳理 header() 的核心用法、常見失敗原因,並提供最佳實踐方案。
header() 用於發送原始 HTTP 標頭,主要用途包括:
Location 標頭讓瀏覽器自動跳轉至指定 URL。Content-Type: application/json、application/pdf 等,告訴瀏覽器如何解析回應內容。Content-Disposition: attachment 強制瀏覽器下載而非直接開啟。Cache-Control、Expires、Pragma 等標頭。header(string $header, bool $replace = true, int $http_response_code = 0): void
true;設為 false 可發送多個同名標頭。<?php
header("Location: https://www.example.com/");
exit; // 防止後續程式碼繼續執行
?>
<?php
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");
header("Pragma: no-cache"); // HTTP/1.0 相容
?>
<?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"); // 此寫法在某些環境下可能無效
?>
<?php
header("Content-Type: audio/mpeg");
header('Content-Disposition: attachment; filename="song.mp3"');
header("Content-Description: PHP Generated Data");
readfile('/path/to/real/song.mp3');
?>
錯誤訊息:
Warning: Cannot modify header information - headers already sent by (output started at /path/file.php:12) in /path/file.php on line 20
PHP 執行機制:腳本啟動時,HTTP 標頭與主體內容分開發送。標頭會被暫存於列表中,直到腳本輸出第一個非標頭內容(HTML 文字、echo、print、空白行、BOM 標記等),PHP 才會一次性發送所有標頭並結束標頭階段。此後再呼叫 header()、setcookie()、session_start() 皆會觸發錯誤。
<?php ... ?> 標籤間的空白行、換行echo、print、var_dump 等輸出語句header() 呼叫前零輸出,包含空白字元。php.ini:output_buffering = 4096(或 On)ob_start(),結尾 ob_end_flush()原理:開啟緩衝後,輸出不會直接送至瀏覽器,而是暫存於記憶體緩衝區,標頭仍可隨時修改;腳本結束時 PHP 自動先送標頭再送內容。
| 範圍 | 含義 |
|---|---|
| 1xx | 資訊回應(保留) |
| 2xx | 成功(200 OK、201 Created) |
| 3xx | 重定向(301 永久、302 暫時、304 Not Modified) |
| 4xx | 用戶端錯誤(400 Bad Request、401 Unauthorized、403 Forbidden、404 Not Found) |
| 5xx | 伺服器錯誤(500 Internal Server Error、502 Bad Gateway、503 Service Unavailable) |
https://)。header("Location: ...") 後緊接 exit;。ob_start(),統一管理輸出緩衝。error_reporting(E_ALL) 開發階段捕捉隱性輸出。掌握 header() 的運作機制與輸出緩衡原理,就能徹底解決重定向失效、標頭衝突等經典難題,讓 PHP 應用更穩健、可維護。