Cookie 是伺服器儲存在瀏覽器的小型資料片段,常用於識別用戶、記住偏好、追蹤行為。本文涵蓋設定、讀取、刪除與安全最佳實務。
setcookie(
string $name,
string $value = "",
int $expires_or_options = 0,
string $path = "",
string $domain = "",
bool $secure = false,
bool $httponly = false
): bool
<?php
// 1. 設定 Cookie(必須在任何輸出之前)
// 記住登入 30 天,全站可用,僅 HTTPS 傳輸,JS 無法讀取
setcookie('remember_token', $token, [
'expires' => time() + 30*24*3600,
'path' => '/',
'domain' => '', // 當前域名
'secure' => true, // 僅 HTTPS
'httponly' => true, // 防 XSS 竊取
'samesite' => 'Lax', // CSRF 防護
]);
// 2. 讀取 Cookie
if (isset($_COOKIE['remember_token'])) {
$token = $_COOKIE['remember_token'];
// 驗證 token 有效性...
}
// 3. 刪除 Cookie(設定過期時間為過去)
setcookie('remember_token', '', [
'expires' => time() - 3600,
'path' => '/',
'secure' => true,
'httponly'=> true,
]);
// 4. 陣列式 Cookie(自動序列化)
setcookie('prefs[theme]', 'dark', time()+86400, '/');
setcookie('prefs[lang]', 'zh-TW', time()+86400, '/');
// 讀取:$_COOKIE['prefs'] => ['theme'=>'dark', 'lang'=>'zh-TW']
?>
| 問題 | 原因 | 解決 |
|---|---|---|
| Cookie 設定失效 | 在 setcookie() 前已有輸出(空白、BOM、echo) | 確保最頂端呼叫,或開啟 output_buffering |
| 子域名共享 | Domain 設定錯誤 | 設定 domain => '.example.com' (前綴點號) |
| HTTPS 環境無法讀取 | 未設 secure => true | 正式環境必須啟用 Secure 標誌 |
| JS 竊取 Cookie | 未設 HttpOnly | 永遠啟用 httponly => true |