| 場景 | 推薦方式 | 關鍵點 |
|---|---|---|
| 表單提交後(同步) | Session Flash + Header Redirect | PRG 模式、避免重複提交 |
| AJAX / API 請求 | JSON 回應 + 前端路由 | 無刷新、體驗流暢 |
| 傳統頁面需強提示 | JS Alert / SweetAlert2 | 確保使用者知曉 |
| 無 JS 環境 / 爬蟲 | Meta Refresh + 鏈接降級 | 可訪問性 |
// 處理表單提交
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 驗證、業務邏輯...
$success = doBusinessLogic($_POST);
$_SESSION['flash'] = [
'type' => $success ? 'success' : 'error',
'message' => $success ? '操作成功!' : '操作失敗:' . $errorMsg,
];
// 303 See Other 強制 GET 重導,防止重新提交
header('Location: ' . $_SERVER['HTTP_REFERER'] ?? '/', true, 303);
exit;
}
// 頁面模板顯示 Flash
if (!empty($_SESSION['flash'])) {
$flash = $_SESSION['flash'];
unset($_SESSION['flash']);
echo "<script>
document.addEventListener('DOMContentLoaded', () => {
Swal.fire({
icon: '" . json_encode($flash['type']) . "',
text: " . json_encode($flash['message']) . ",
timer: 2000,
showConfirmButton: false
});
});
</script>";
}
function alertAndRedirect(string $msg, string $url, int $delayMs = 1500): never {
// XSS 安全編碼
$jsMsg = json_encode($msg, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
$jsUrl = json_encode($url, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
echo "<!DOCTYPE html><html><head><meta charset='utf-8'></head><body>";
echo "<script>";
echo "alert($jsMsg);";
echo "setTimeout(() => { window.location.href = $jsUrl; }, $delayMs);";
echo "</script>";
echo "<p>若未跳轉,請點擊 <a href='$jsUrl'>這裡</a></p>";
echo "</body></html>";
exit;
}
// 使用
alertAndRedirect('資料已刪除', '/list.php');
function metaRedirect(string $msg, string $url, int $delaySec = 2): never {
$safeMsg = htmlspecialchars($msg, ENT_QUOTES, 'UTF-8');
$safeUrl = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
echo "<!DOCTYPE html><html><head><meta charset='utf-8'>";
echo "<meta http-equiv='refresh' content='$delaySec;url=$safeUrl'>";
echo "<title>跳轉中...</title></head><body>";
echo "<p>$safeMsg</p>";
echo "<p><a href='$safeUrl'>點擊這裡手動跳轉</a></p>";
echo "</body></html>";
exit;
}
function sweetRedirect(string $title, string $text, string $url, string $icon = 'success'): never {
$payload = json_encode([
'title' => $title,
'text' => $text,
'icon' => $icon,
'timer' => 2000,
'showConfirmButton' => false,
], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
$jsUrl = json_encode($url, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
echo "<!DOCTYPE html><html><head><meta charset='utf-8'>";
echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>";
echo "</head><body><script>";
echo "Swal.fire($payload).then(() => { window.location.href = $jsUrl; });";
echo "</script></body></html>";
exit;
}
Response::redirectWithMessage() 靜態方法,避免分散重複代碼。json_encode() + JSON_HEX_* 旗標處理。header('Location:') 前絕無任何輸出(含 BOM、空白、錯誤訊息),必要時 ob_clean()。303,永久遷移用 301,臨時用 302/307。// Laravel
return redirect()->route('home')->with('success', '歡迎回來!');
// ThinkPHP 6
return redirect('index')->with('msg', '操作成功');
// Symfony
$this->addFlash('success', '已儲存');
return $this->redirectToRoute('home');
// CodeIgniter 4
return redirect()->to('/home')->with('message', '成功');
現代 Web 應用應以 PRG + Session Flash + 前端 Toast 為主流模式,傳統 alert() 仅用於極簡單場景或維護舊系統。核心原則:安全編碼、語義狀態碼、優雅降級、統一封裝。