首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 頁面跳轉完整指南:Header、JavaScript、Meta Refresh 多種方式詳解與避坑

     編輯:PHP 相關知識

PHP 實現頁面跳轉主要有三大類方式,各有適用場景與限制。本文系統整理 header()、JavaScript、HTML Meta Refresh 等跳轉技術,並重點分析常見錯誤與最佳實踐。

一、PHP header() 重定向(服務端、推薦)

基本語法

<?php
// 標準跳轉
$url = "https://example.com/page.php";
header("Location: $url");
exit; // 關鍵:防止後續代碼繼續執行
?>

實戰案例:域名遷移自動跳轉

<?php
$url_this = strtolower('https://' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]);
$go_url = str_replace('https://www.old-domain.com/blog', 'https://www.new-domain.com', $url_this);
header("Location: $go_url");
exit;
?>

header() 關鍵參數詳解

void header(string $header, bool $replace = true, int $http_response_code = 0)
  • $replace:是否替換同類型頭信息,默認 true
  • $http_response_code:強制設置 HTTP 狀態碼(如 301 永久重定向、302 臨時重定向)

⚠️ 三大鐵律(違反必報錯)

  1. Location 後無空格:header("Location: $url") ✓ | header("Location : $url") ✗
  2. 輸出前調用:header 前不能有任何輸出(包括空白字符、BOM 頭、echo/print 等)
  3. 代碼繼續執行:header 後代碼仍會執行,必須配合 exit/die

二、JavaScript 跳轉(客戶端、靈活)

適用場景

  • 已有輸出內容無法使用 header()
  • 需延遲跳轉、倒計時提示
  • 條件判斷後動態決定跳轉

代碼實例

<?php
$url = "https://example.com";
echo "<script>window.location.href='$url';</script>";
// 或帶延遲
echo "<script>setTimeout(function(){window.location.href='$url';}, 3000);</script>";
?>

三、HTML Meta Refresh(靜態頁、郵件模板)

語法格式

<meta http-equiv="refresh" content="秒數; url=目標網址" />

實例

<!-- 5秒後刷新本頁 -->
<meta http-equiv="refresh" content="5" />

<!-- 5秒後跳轉到首頁 -->
<meta http-equiv="refresh" content="5; url=https://example.com" />

<!-- 立即跳轉(0秒) -->
<meta http-equiv="refresh" content="0; url=https://example.com" />

四、表單提交後跳轉(POST-Redirect-GET 模式)

<!-- 表單頁 -->
<form action="process.php" method="post">
    <input type="text" name="name" />
    <input type="submit" name="submit" value="提交" />
</form>

<!-- process.php 處理邏輯 -->
<?php
if (isset($_POST["name"])) {
    // 業務處理...
    header("Location: success.php?name=" . urlencode($_POST["name"]));
    exit;
}
?>

注意:處理頁面不能有任何輸出,否則 header 失效報錯。

五、HTTP 狀態碼選擇指南

狀態碼含義適用場景SEO 影響
301Moved Permanently域名遷移、URL 永久變更傳遞權重,搜索引擎更新索引
302Found (臨時重定向)登錄後跳轉、臨時維護頁面不傳遞權重,保留原 URL 索引
303See OtherPOST 請求處理後跳轉強制 GET 請求,防止重複提交
307Temporary Redirect保持原請求方法的臨時跳轉保持 POST 數據,現代瀏覽器支持

設置狀態碼示例

<?php
// 永久重定向(SEO 友好)
header("Location: https://new-domain.com", true, 301);
exit;

// POST 後跳轉(防重複提交)
header("Location: success.php", true, 303);
exit;
?>

六、綜合避坑檢查清單

  • [ ] header() 前無任何輸出(檢查 BOM、空白行、include 文件)
  • [ ] Location 語法正確(冒號後有空格、URL 完整)
  • [ ] 關鍵跳轉後使用 exit/die
  • [ ] 根據業務選擇正確 HTTP 狀態碼
  • [ ] JavaScript 跳轉作為 header 不可用時的備選方案
  • [ ] 避免無限重定向循環(設置最大跳轉次數)

掌握這些技巧,能應對從簡單頁面跳轉到複雜 OAuth 回調、支付回調、多域名遷移等各類場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved