萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實現頁面跳轉的三種方式與最佳實踐

方法一:header() 重導向(推薦,伺服器端 302)

<?php
// 必須在任何輸出之前呼叫
header("Location: https://www.example.com/target.php", true, 302);
exit; // 關鍵:防止後續代碼繼續執行
?>

注意事項:

  • Location: 後無空格(Location:https://...)
  • 前面不能有任何輸出(含 BOM、空白、echo)
  • 預設 302 Found,永久轉向用 301
  • exit 必加,否則腳本繼續跑完

方法二:HTML Meta Refresh(客戶端跳轉)

<!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() 時。

方法三:JavaScript 跳轉(客戶端)

<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 傳遞權重)
?>

常見坑點

  • BOM 檔案編碼:儲存 PHP 檔為 UTF-8 without BOM,否則 BOM 視為輸出導致 headers_sent() 為真。
  • Session 衝突:跳轉前 session_write_close() 釋放鎖,避免並發請求阻塞。
  • 攜帶參數:header("Location: $url?" . http_build_query($params))
copyright © 萬盛學電腦網 all rights reserved