header("Location: ...") 是 PHP 執行頁面重導向的標準方式,但新手常因輸出順序、空格、編碼、執行流程控制等問題導致失效。本文整理四大核心注意事項、與 ASP 對比、常見錯誤場景及解決方案。
header("Location: url") ✓ / header("Location : url") ✗<?php 前的換行。exit() 或 die()。| 特性 | ASP Response.Redirect | PHP header() |
|---|---|---|
| 可在輸出 HTML 後呼叫 | 是(緩衝區預設開啟) | 否(除非開啟 output_buffering) |
| 執行後腳本是否繼續 | 否(隱含終止) | 是(需自行 exit) |
| 多次重導向行為 | 第一次生效 | 最後一次生效 |
<% Response.Redirect "../test.asp" %> ...
echo、print、HTML 空白在 header() 之前。output_buffering = On(php.ini)或腳本開頭 ob_start()。exit(),後續程式碼輸出內容干擾瀏覽器跳轉。Location 值為相對路徑,建議使用絕對 URL:header("Location: https://{$_SERVER['HTTP_HOST']}/target.php")。header("Location: ...", true, 301)。$url = "search.php?kw=" . urlencode("關鍵字");
header("Location: $url");
...錯誤提示...
header("Refresh: 3; url=target.php"); 3 秒後跳轉,配合顯示「3 秒後自動跳轉」訊息。{"redirect": "url"},前端 JS 執行 location.href = data.redirect。session_set_cookie_params() 設定正確 domain、path、secure、httponly。header() 前是否有任何輸出(含空白、include 檔案的輸出)?Location: 後有無多餘空格?header() 後是否緊接 exit()?遵循上述規範,即可避開 99% 的 header() 跳轉失敗問題,確保導向行為穩定可預期。