在 Web 開發中,經常需要在顯示提示信息幾秒鐘後自動跳轉到目標頁面(如登錄成功後跳轉首頁)。PHP 提供了簡單的 Header 方式,也可結合 HTML Meta 標籤或 JavaScript 實現更靈活的延時跳轉。
使用 header() 發送 Refresh 頭,瀏覽器會在指定秒數後自動跳轉。
<?php
// 5 秒後跳轉到 index.php
header("Refresh:5;url=index.php");
echo "登錄成功,5 秒後自動跳轉首頁...";
// 注意:header 必須在任何輸出之前調用
優點:服務端控制,無需依賴前端腳本;缺點:必須在輸出前調用,且無法在跳轉前執行複雜邏輯。
在頁面 <head> 中添加 meta 刷新標籤。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="5;url=index.php">
<title>跳轉提示</title>
</head>
<body>
<p>操作成功,5 秒後自動跳轉...</p>
</body>
</html>
此法不受 PHP 輸出限制,適合在模板文件中直接使用。
結合 setTimeout 可實現倒計時顯示、條件跳轉等高級效果。
<script>
var count = 5;
var timer = setInterval(function() {
count--;
document.getElementById('countdown').innerText = count;
if (count <= 0) {
clearInterval(timer);
window.location.href = 'index.php';
}
}, 1000);
</script>
<p>操作成功,<span id="countdown">5</span> 秒後自動跳轉...</p>
header("Refresh:..."),代碼最少。header(),會導致 "Headers already sent" 錯誤。