頁面跳轉是 Web 開發最高頻操作之一。PHP 提供多種方式,各有適用場景與注意事項。本文系統整理三大主流方法,並給出生產環境最佳實踐建議。
<?php
// 基本用法
header("Location: https://example.com/target-page");
exit; // 關鍵:防止後續程式碼繼續執行
Location: 後**不可有空格**(Location:https://... 錯誤,正確 Location: https://...)。302 Found,若需永久導向用 header("Location: ...", true, 301);。header() 後的程式碼**仍會執行**,務必加 exit 或 die()。<?php
// 攜帶查詢字串
$params = http_build_query(['msg' => '登入成功', 't' => time()]);
header("Location: /dashboard?$params");
exit;
// 延遲 3 秒跳轉(需配合 HTML meta 或 JS,header 無法直接延遲)
// 見方法二、三
<?php
$url = 'https://example.com';
$delay = 3; // 秒
?>
頁面跳轉中...
= $delay ?> 秒後自動跳轉至 目標頁面...
header()。<?php
$url = 'https://example.com';
?>
| 維度 | header() | <meta> | JavaScript |
|---|---|---|---|
| 執行端 | 伺服器 (HTTP 302) | 客戶端 (HTML 解析) | 客戶端 (JS 引擎) |
| SEO 友善 | ✅ 301/302 標準 | ⚠️ 延遲、非標準 | ❌ 爬蟲可能不執行 JS |
| 延遲跳轉 | ❌ 需配合 sleep/輸出 | ✅ 原生支援 | ✅ setTimeout |
| 攜帶 POST 資料 | ❌ 僅 GET | ❌ | ✅ 可配合 form.submit() |
| 受輸出限制 | ⚠️ 嚴格禁止前輸出 | ✅ 任意位置 | ✅ 任意位置 |
| 歷史紀錄 | ✅ 可控 (301/302) | ❌ 保留中介頁 | 可控 (replace/href) |
header() + exit,確保無輸出前置(可用 ob_start() 緩衝輸出)。window.location.href = res.url),勿在 AJAX 中輸出 HTML/JS。from_url、to_url、user_id 供稽核。<?php
// ❌ 錯誤:header 前有空白輸出
echo " ";
header("Location: /"); // Warning: Cannot modify header information
// ✅ 正確:ob_start 緩衝或調整程式碼順序
ob_start();
// ... 業務邏輯 ...
header("Location: /");
exit;
// ❌ 錯誤:Location 格式錯誤
header("Location:https://a.com"); // 缺空格
// ✅ 正確
header("Location: https://a.com");
**伺服器端 header() 是首選**,符合 HTTP 標準、SEO 友善、效能最佳;** 適合需顯示過渡訊息的傳統頁面**;**JavaScript 適合 AJAX/SPA/條件跳轉**。根據場景選擇,並嚴守「無前置輸出」、「白名單驗證」、「加 exit」三大鐵律。