<?php
// 必須在任何輸出之前調用
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP/1.1
header("Pragma: no-cache"); // HTTP/1.0 兼容
header("Expires: -1"); // 過期時間設為過去
| Header | 協議版本 | 作用 |
|---|---|---|
Cache-Control: no-cache, no-store, must-revalidate | HTTP/1.1 | no-cache 強制驗證,no-store 禁止任何緩存,must-revalidate 過期必須回源驗證 |
Pragma: no-cache | HTTP/1.0 | 舊瀏覽器/代理兼容,語義同 Cache-Control: no-cache |
Expires: -1 / Expires: 0 | HTTP/1.0+ | 過期時間設為過去,強制視為過期 |
<?php
// 訂單確認頁(第 2 步)
session_start();
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: -1");
if (empty($_SESSION['cart'])) {
header("Location: cart.php"); // 購物車為空跳回
exit;
}
// 顯示收貨地址、付款方式表單
?>
用戶在第 3 步生成訂單後點「返回」,瀏覽器不會使用緩存,重新請求第 2 步頁面,PHP 發現購物車已清空,自動跳轉至空購物車頁,避免重複下單。
no-store 支持最佳,建議保留。no-store 以便「返回」功能,但上述組合仍能覆蓋 99% 場景。// 錯誤:HTML meta 標籤不可靠,代理服務器不解析
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
只能作為補充,**必須**使用 PHP header() 發送真實 HTTP 頭。