PHP 實作自動頁面跳轉主要有三種主流方式:HTTP Header 重導向、HTML Meta Refresh、JavaScript 跳轉。各有優缺點與適用場景,本文提供完整語法、比較表與最佳實踐建議。
<?php
// 立即跳轉 (302 Found)
header('Location: https://example.com/target.php');
exit;
// 延遲跳轉需配合 HTML/JS,Header 無法直接延遲
// 若需延遲顯示提示訊息,改用 Meta Refresh 或 JavaScript
?>
exit 或 die() 防止後續程式碼執行<?php
$url = 'https://example.com/target.php';
$delay = 5; // 秒
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="<?= $delay ?>;url=<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>">
<title>跳轉中...</title>
</head>
<body>
<p><?= $delay ?> 秒後自動跳轉至 <a href="<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>">目標頁面</a></p>
</body>
</html>
header()<?php
$url = 'https://example.com/target.php';
?>
<script>
// 立即跳轉(取代歷史記錄,避免「上一頁」回跳)
window.location.replace('<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>');
// 延遲跳轉
// setTimeout(() => window.location.href = '...', 3000);
</script>
<noscript>
<meta http-equiv="refresh" content="0;url=<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>">
</noscript>
<?php
$userRole = $_SESSION['role'] ?? 'guest';
$targets = [
'admin' => '/admin/dashboard',
'editor' => '/editor/workspace',
'guest' => '/login',
];
$url = $targets[$userRole] ?? '/403';
?>
<script>window.location.replace('<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>');</script>
| 特性 | Header | Meta Refresh | JavaScript |
|---|---|---|---|
| 執行階段 | 伺服器回應階段 | 瀏覽器解析 HTML 階段 | 瀏覽器執行 JS 階段 |
| HTTP 狀態碼 | 301/302/303/307/308 | 200 OK | 200 OK |
| SEO 傳遞權重 | 是 (301/308) | 否 | 否 |
| 支援延遲 | 否 | 是 | 是 |
| 需在輸出前 | 是 | 否 | 否 |
| 歷史記錄處理 | 瀏覽器決定 | 保留中介頁 | 可用 replace() 移除 |
| 無腳本環境支援 | 是 | 是 | 否 (需 noscript 降級) |
header() + exitMeta RefreshJavaScript (location.replace())掌握三種跳轉方式的差異,根據業務場景選擇最適合的方案,並遵循安全與 SEO 最佳實踐,即能優雅地實作 PHP 自動頁面跳轉。