清除 Cookie 的本質是設定過期時間為過去時間點,瀏覽器即會自動刪除。三語言語法不同,邏輯一致。
function deleteCookie(name, domain, path) {
var exp = new Date();
exp.setTime(exp.getTime() - 1); // 過去時間
document.cookie = name + "=; expires=" + exp.toGMTString()
+ "; path=" + (path || "/")
+ "; domain=" + (domain || document.domain);
}
// 使用範例
deleteCookie("user_token");
deleteCookie("shop_cart", ".example.com", "/shop");
' 方法 1: 設定 Expires 為過去
Response.Cookies("mycookie").Expires = DateAdd("d", -1, Now())
' 方法 2: 明確指定路徑與域名 (跨子域名時需指定)
Response.Cookies("mycookie").Expires = DateAdd("d", -1, Now())
Response.Cookies("mycookie").Path = "/"
Response.Cookies("mycookie").Domain = ".example.com" ' 注意前綴點號
' 方法 3: 直接指派空值並過期 (部分舊版 IIS 需此寫法)
Response.Cookies("mycookie") = ""
Response.Cookies("mycookie").Expires = DateAdd("d", -1, Now())
<?php
// 標準寫法:時間設為過去
setcookie("memusername", "", time() - 3600, "/", ".example.com", false, true);
// 參數:名稱、值、過期時間、路徑、域名、secure、httponly
// 簡寫 (僅名稱)
setcookie("memusername"); // 等同設為空值並過期
?>
| 參數 | JS | ASP | PHP |
|---|---|---|---|
| 名稱 | name | Response.Cookies(name) | $name |
| 值 | =value | =value | $value |
| 過期 | expires=GMTString | .Expires = date | $expire (timestamp) |
| 路徑 | path=/ | .Path = "/" | $path |
| 域名 | domain=.example.com | .Domain = ".example.com" | $domain |
| Secure | secure | .Secure = True | $secure |
| HttpOnly | httponly (需支援) | .HttpOnly = True (IIS 7+) | $httponly |
主域名 example.com 下的子域名 a.example.com、b.example.com 共享 Cookie:
Domain = ".example.com" (前綴點號)HttpOnly 防 XSS、Secure 強制 HTTPS掌握三語言清除 Cookie 寫法,配合域名/路徑精確控制,是多系統整合與安全登出的基本功。