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

PHP 實現帶倒計時的頁面自動跳轉

     編輯:PHP 相關知識

核心原理

利用 HTML `` 實現瀏覽器端無 JS 跳轉,配合倒計時提升用戶體驗。

通用跳轉函數

<?php
/**
 * 頁面跳轉提示
 * @param string $url      目標 URL
 * @param string $message  提示信息
 * @param int    $seconds  延遲秒數
 */
function redirectWithMessage(string $url, string $message = '頁面跳轉中...', int $seconds = 3): void {
    // 防止頭部已發送
    if (headers_sent()) {
        // 降級:JS 跳轉
        echo "<script>setTimeout(() => location.href = " . json_encode($url) . ", {$seconds}000);</script>";
        echo "<p>$message</p>";
        exit;
    }

    // 發送狀態碼(可選)
    // header('HTTP/1.1 302 Found'); // 臨時跳轉
    // header("Refresh: $seconds; url=$url"); // HTTP 頭方式(不如 meta 兼容)

    // 輸出完整 HTML
    echo '<!DOCTYPE html>';
    echo '<html><head><meta charset="UTF-8">';
    echo '<title>頁面跳轉</title>';
    echo '<meta http-equiv="refresh" content="' . $seconds . ';url=' . htmlspecialchars($url, ENT_QUOTES) . '">';
    echo '<style>
        body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f5f5f5}
        .box{background:#fff;padding:2rem;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,.1);text-align:center;max-width:400px}
        h1{margin:0 0 1rem;color:#333}
        .countdown{font-size:1.5rem;color:#007bff;font-weight:bold}
        a{color:#007bff;text-decoration:none}
    </style>';
    echo '</head><body><div class="box">';
    echo '<h1>' . htmlspecialchars($message) . '</h1>';
    echo '<div class="countdown" id="cd">' . $seconds . '</div>';
    echo '<p>如果瀏覽器未自動跳轉,請點擊 <a href="' . htmlspecialchars($url, ENT_QUOTES) . '">這裡</a></p>';
    echo '</div>';
    echo '<script>
        let s = ' . $seconds . ';
        const el = document.getElementById("cd");
        const timer = setInterval(() => {
            s--;
            if (s > 0) el.textContent = s;
            else { clearInterval(timer); }
        }, 1000);
    </script>';
    echo '</body></html>';
    exit;
}

// 使用示例
// redirectWithMessage('/dashboard', '登錄成功,正在跳轉...', 2);
?>

進階:AJAX 請求專用跳轉

AJAX 不能直接跟隨 `meta refresh`,需返回 JSON 讓前端處理:

<?php
function ajaxRedirect(string $url, string $message = '操作成功'): void {
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode([
        'code' => 0,
        'msg' => $message,
        'redirect' => $url,
    ]);
    exit;
}

// 前端 JS
fetch(url, {method:'POST', body:formData})
    .then(r => r.json())
    .then(data => {
        if (data.code === 0 && data.redirect) {
            setTimeout(() => location.href = data.redirect, 1500);
            showToast(data.msg);
        }
    });

HTTP 狀態碼選擇指南

場景狀態碼PHP 代碼
表單提交成功,重定向到列表頁303 See Otherheader('Location: /list', true, 303);
登錄成功,跳轉儀表盤302 Foundheader('Location: /dashboard', true, 302);
永久遷移(SEO 權重傳遞)301 Moved Permanentlyheader('Location: /new-url', true, 301);
需顯示提示信息再跳轉200 OK + meta refreshredirectWithMessage()

注意事項

  • 必須在任何輸出前調用(含空白、BOM、錯誤信息)。
  • URL 需 `htmlspecialchars($url, ENT_QUOTES)` 防 XSS。
  • 生產環境建議**日誌記錄跳轉來源與目標**,便於排查異常跳轉鏈。

總結

`redirectWithMessage()` 封裝了「友好提示 + 倒計時 + 降級鏈接 + JS 倒計時動畫」,開箱即用。AJAX 場景返回 JSON 由前端控制跳轉。核心原則:**輸出前調用、URL 轉義、狀態碼語義化**。

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