萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP header() 重定向失效?完整排查指南與 HTTP 標頭詳解

header() 基本功能

header() 用於發送原始 HTTP 標頭,三大核心用途:

  1. 頁面跳轉:Location: URL
  2. 指定內容類型:Content-Type: application/json
  3. 檔案下載:Content-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');
?>

HTTP 狀態碼速查

  • 1xx:資訊回應
  • 2xx:成功(200 OK, 201 Created, 204 No Content)
  • 3xx:重定向(301 永久, 302 暫時, 304 Not Modified)
  • 4xx:客戶端錯誤(400, 401, 403, 404, 414 URI Too Long)
  • 5xx:伺服器錯誤(500, 502, 503, 504)

header() 完整語法

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) 捕獲警告。
  • 用瀏覽器開發者工具 Network 分頁查看 Response Headers。
  • 檢查 php.ini 的 output_buffering 設定(On 可容忍少量前置輸出)。
copyright © 萬盛學電腦網 all rights reserved