Cookie 是 document 物件的屬性,本質為鍵值對字串,儲存在用戶端硬碟 (或記憶體)。伺服器透過 Set-Cookie Header 下發,瀏覽器自動攜帶於後續請求的 Cookie Header 中。定義於 RFC 6265 (取代 RFC 2109/2965)。
| 屬性 | 說明 | 預設值 | 安全影響 |
|---|---|---|---|
Expires / Max-Age | 生存期。Expires=Wed, 21 Oct 2025 07:28:00 GMT (GMT 格式) 或 Max-Age=3600 (秒數,優先級較高) | Session Cookie (瀏覽器關閉即失效) | 長期 Cookie 增加追蹤風險,敏感資料勿存 |
Path | 生效路徑前綴。/ 為全站,/admin 僅 /admin 及子路徑 | 設定 Cookie 的頁面路徑 | 過寬路徑導致不必要攜帶,洩露風險 |
Domain | 生效網域。example.com (不含子網域) vs .example.com (含子網域) | 當前主機名 (不含子網域) | 不可跨主域設定 (如 .com),防禦超級 Cookie |
Secure | 僅 HTTPS 傳輸 | false | 生產環境必開,防中間人竊取 |
HttpOnly | 禁止 JS 存取 (document.cookie 不可讀寫) | false | 防 XSS 竊取 Session ID 必開 |
SameSite | 跨站請求攜帶策略:Strict/Lax/None | Lax (現代瀏覽器) | Strict 最嚴格防 CSRF,None 需配合 Secure 用於跨站嵌入 |
// 寫入 (值需 encodeURIComponent)
document.cookie = 'version=' + encodeURIComponent('1.0.0') + '; path=/; max-age=3600; SameSite=Lax';
// 讀取:分號分隔的 key=value 字串
function getCookie(name) {
const match = document.cookie.match(new RegExp('(^|;\\s*)' + name + '=([^;]+)'));
return match ? decodeURIComponent(match[2]) : null;
}
// 刪除:設定過期時間為過去
document.cookie = 'version=; max-age=0; path=/';
<?php
// 設定 (需在輸出前)
setcookie('session_id', 'abc123', [
'expires' => time() + 3600,
'path' => '/',
'domain' => '.example.com', // 含子網域
'secure' => true, // 僅 HTTPS
'httponly' => true, // 防 XSS
'samesite' => 'Lax', // CSRF 保護
]);
// 讀取
$sessionId = $_COOKIE['session_id'] ?? null;
// 刪除
setcookie('session_id', '', ['expires' => time() - 3600, 'path' => '/']);
?>
Network/Cookies (加密儲存,需 DPAPI/Keychain 解密)。cookies.sqlite (profile 目錄)。Cookies.binarycookies。Temporary Internet Files 目錄下。Secure + HttpOnly + SameSite=Strict,Max-Age 短 (15-30 分鐘),閒置輪換。Secure + HttpOnly + SameSite=Lax,資料庫存雜湊值,定期輪換。__Host- (需 Secure+Path=/) / __Secure- (需 Secure) 前綴,瀏覽器強制驗證屬性。