header() 用於發送原始 HTTP 標頭,三大核心用途:
Location: URLContent-Type: application/jsonContent-Disposition: attachment; filename=...| 原因 | 現象 | 解決 |
|---|---|---|
| 輸出已送出(echo、空白、BOM) | Warning: Cannot modify header information | 確保 header() 前無任何輸出;用 ob_start() 緩衝 |
| 大小寫/拼寫錯誤 | 瀏覽器不跳轉 | 標準寫法:header('Location: https://example.com'); |
| 相對路徑 | 跳轉錯誤 | 使用絕對 URL(含 scheme) |
| 未終止腳本 | 後續代碼繼續執行 | 跳轉後立即 exit; |
| 編碼問題(中文 URL) | 跳轉異常 | 使用 urlencode() 編碼參數 |
<?php
// 301 永久重定向(SEO 傳遞權重)
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://new-domain.com' . $_SERVER['REQUEST_URI']);
exit;
// 302 暫時重定向(預設)
header('Location: https://example.com/login.php');
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-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
?>
header(string $header, bool $replace = true, int $http_response_code = 0): void
$replace:true 替換同類標頭(預設),false 允許多個同名標頭(如多個 Set-Cookie)。$http_response_code:強制指定狀態碼(PHP 4.3+)。error_reporting(E_ALL) 捕獲警告。php.ini 的 output_buffering 設定(On 可容忍少量前置輸出)。