Cookie 是伺服器要求瀏覽器在本地儲存的小型資料片段,隨後每次請求自動攜帶回伺服器。常用於:身分識別、偏好設定、追蹤、購物車等。
<?php
// 基本設定:名稱、值、過期時間(Unix 時間戳)
setcookie('user_pref', 'dark_mode', time() + 86400); // 1 天後過期
// 完整參數:名稱、值、過期、路徑、域名、Secure、HttpOnly
setcookie('auth_token', 'abc123', [
'expires' => time() + 3600, // 1 小時
'path' => '/', // 整站可用
'domain' => '.example.com', // 共享給子域 (前綴 .)
'secure' => true, // 僅 HTTPS
'httponly' => true, // 防 JS 存取 (XSS 防護)
'samesite' => 'Lax', // CSRF 防護 (Strict/Lax/None)
]);
// 陣列型 Cookie(自動序列化為多個同名 Cookie)
setcookie('cart[item1]', 'sku_001');
setcookie('cart[item2]', 'sku_002');
// $_COOKIE['cart'] = ['item1' => 'sku_001', 'item2' => 'sku_002']
?>
<?php
// $_COOKIE 超全域陣列自動解析所有 Cookie
echo $_COOKIE['user_pref'] ?? '未設定'; // dark_mode
// 印出所有 Cookie
print_r($_COOKIE);
/*
Array
(
[user_pref] => dark_mode
[auth_token] => abc123
[cart] => Array ( [item1] => sku_001 [item2] => sku_002 )
[PHPSESSID] => abc123...
)
*/
?>
<?php
// 設定過期時間為過去
setcookie('user_pref', '', time() - 3600, '/', '.example.com', true, true);
// 或 PHP 7.3+ 陣列語法
setcookie('user_pref', '', [
'expires' => time() - 3600,
'path' => '/',
'domain' => '.example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
?>
| 參數 | 說明 | 建議值 |
|---|---|---|
expires | 過期 Unix 時間戳;0 或省略 = 會話期限 (關閉瀏覽器失效) | 依業務需求 (如 3600, 86400) |
path | Cookie 生效路徑 | / (全站) |
domain | Cookie 生效域名;.example.com 包含子域 | 主域名或 .example.com |
secure | 僅 HTTPS 傳送 | true (正式環境必開) |
httponly | 禁止 JavaScript 存取 (document.cookie) | true (防 XSS) |
samesite | 跨站請求攜帶策略 | Lax (平衡體驗/安全) 或 Strict |
<?php
// 主域 example.com 設定 Cookie 給 .example.com
setcookie('shared_token', 'value', [
'expires' => time() + 86400,
'path' => '/',
'domain' => '.example.com', // 關鍵:前綴點號
'secure' => true,
'httponly' => true,
'samesite' => 'None', // 跨站需求時用 None (必須配合 Secure)
]);
// 子域 api.example.com、app.example.com 皆可讀取 $_COOKIE['shared_token']
?>
hash_hmac() 簽名或 openssl_encrypt() 加密。Lax 允許連結導航攜帶,Strict 完全阻擋跨站,None 需 Secure 且用於跨域 API。| 現象 | 可能原因 | 解決 |
|---|---|---|
| Cookie 未送達伺服器 | 域名/路徑不匹配、SameSite 阻擋、Secure 不符 | 檢查 domain/path/secure/samesite 設定 |
| 子域讀不到主域 Cookie | 主域未設 domain=.example.com | 加上前綴點號 |
| JS 讀不到 Cookie | httponly=true | 非敏感 Cookie 可設 httponly=false,但增加 XSS 風險 |
| 中文值亂碼 | Cookie 標準僅支援 ASCII | 值需 urlencode() 編碼,讀取時 urldecode() |
Cookie 是 HTTP 狀態管理的基石。正確設定 expires、path、domain、secure、httponly、samesite 六大屬性,並遵循「最小權限、敏感資料不入 Cookie、簽名驗證」原則,即可安全、可靠地使用 Cookie。