<?php
// 必須在任何輸出之前呼叫
header("Location: https://www.example.com/target.php", true, 302);
exit; // 關鍵:防止後續代碼繼續執行
?>
注意事項:
Location: 後無空格(Location:https://...)exit 必加,否則腳本繼續跑完<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="refresh" content="3;url=https://www.example.com/">
<title>正在跳轉...</title>
</head>
<body>
3 秒後自動跳轉,若未跳轉 請點這裡。
</body>
</html>
適用場景:需顯示提示訊息、倒數計時、或已有輸出內容無法用 header() 時。
<script>
// 立即跳轉(替換歷史紀錄,無法回上頁)
location.replace("https://www.example.com/");
// 或保留歷史
// location.href = "https://www.example.com/";
// 延遲跳轉
// setTimeout(() => location.href = "...", 3000);
</script>
<?php
function redirect(string $url, int $statusCode = 302, bool $exit = true): never {
// 清除輸出緩衝(若已有輸出)
if (headers_sent()) {
// 已送標頭,改用 JS/Meta 降級
echo "";
echo "";
if ($exit) exit;
return;
}
header("Location: $url", true, $statusCode);
if ($exit) exit;
}
// 使用
redirect('/dashboard.php', 302);
redirect('https://example.com', 301); // 永久轉向(SEO 傳遞權重)
?>
headers_sent() 為真。session_write_close() 釋放鎖,避免並發請求阻塞。header("Location: $url?" . http_build_query($params))