Cookie 是 HTTP 協定中維持狀態的核心機制。PHP 透過 setcookie() / setrawcookie() 寫入、$_COOKIE 讀取。本文詳細說明完整操作流程、安全屬性 (Secure、HttpOnly、SameSite)、常見陷阱與現代最佳實踐。
<?php
// 語法:setcookie(name, value, expires_or_options, path, domain, secure, httponly)
// PHP 7.3+ 支援陣列選項寫法 (推薦)
setcookie('user_id', '12345', [
'expires' => time() + 3600, // 1 小時後過期 (Unix timestamp)
'path' => '/', // 整站可用
'domain' => 'example.com', // 共享給子網域 (可選)
'secure' => true, // 僅 HTTPS 傳輸
'httponly' => true, // JavaScript 無法讀取 (防 XSS 竊取)
'samesite' => 'Lax' // CSRF 防護:Lax/Strict/None
]);
// 等同舊式寫法 (不推薦)
setcookie('user_id', '12345', time() + 3600, '/', 'example.com', true, true);
?>
<?php
// 自動解析 HTTP Cookie 標頭
$userId = $_COOKIE['user_id'] ?? null;
$allCookies = $_COOKIE; // 所有 Cookie 陣列
?>
<?php
// 設定過期時間為過去時間點
setcookie('user_id', '', [
'expires' => time() - 3600,
'path' => '/',
'domain' => 'example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
// 必須與設定時的 path、domain、secure、samesite 完全一致才能刪除
?>
| 屬性 | 作用 | 建議值 | 備註 |
|---|---|---|---|
Secure | 僅在 HTTPS 連線傳送 | true | 生產環境強制開啟,本地開發可關閉 |
HttpOnly | 禁止 JavaScript 存取 (document.cookie) | true | 防禦 XSS 竊取 Session ID,除非前端需讀取 |
SameSite | 跨站請求攜帶策略 | Lax (預設) | Strict 最嚴格但影響體驗;None 需 Secure,用於跨站嵌入 |
Path | Cookie 生效路徑前綴 | / | 避免過窄導致子路徑無法讀取 |
Domain | 共享網域範圍 | 例: .example.com | 前綴點號表示包含子網域;不設定則僅當前主機 |
Expires/Max-Age | 過期時間 | 視業務需求 | Max-Age 以秒為單位 (PHP 7.3+),優於 Expires |
| 值 | 同站請求 | 跨站連結/GET 表單 | 跨站 POST/iframe/AJAX |
|---|---|---|---|
Strict | ✅ 送出 | ❌ 不送出 | ❌ 不送出 |
Lax (預設) | ✅ 送出 | ✅ 送出 (安全方法) | ❌ 不送出 |
None | ✅ 送出 | ✅ 送出 | ✅ 送出 (需 Secure) |
<?php
// php.ini 或啟動前設定
ini_set('session.cookie_secure', '1'); // 僅 HTTPS
ini_set('session.cookie_httponly', '1'); // 防 XSS
ini_set('session.cookie_samesite', 'Lax'); // CSRF 防護
ini_set('session.use_strict_mode', '1'); // 防 Session Fixation
ini_set('session.cookie_lifetime', '0'); // 瀏覽器關閉即過期 (Session Cookie)
// 手動啟動時也可覆寫
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => 'example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
session_start();
?>
<?php
// 錯誤:setcookie() 前有輸出 (含空白、BOM、HTML)
echo ' ';
setcookie('a', '1'); // Warning: Cannot modify header information
// 正確:setcookie() 必須在任何輸出之前
setcookie('a', '1');
echo 'OK';
解決:開啟 output_buffering = On (php.ini) 或確保邏輯在輸出前。
<?php
// 主網域 example.com,子網域 api.example.com
// 正確:設定 domain 為 .example.com (前綴點號)
setcookie('token', $token, [
'domain' => '.example.com', // 所有子網域可讀
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
// 錯誤:domain 設為 example.com (無點號) → 子網域無法讀取
// 錯誤:domain 設為 api.example.com → 主網域無法讀取
<?php
// 跨站 iframe/嵌入場景需 SameSite=None
setcookie('tracking_id', $id, [
'samesite' => 'None', // 必須
'secure' => true, // 必須 (否則瀏覽器拒絕)
'httponly' => true
]);
<?php
// login.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
$remember = isset($_POST['remember']);
// 驗證用戶 (略)
$user = authenticate($username, $password);
if ($user) {
// 建立長效 Token (資料庫儲存 selector + validator 雜湊)
$selector = bin2hex(random_bytes(16));
$validator = bin2hex(random_bytes(32));
$hashedValidator = hash('sha256', $validator);
$expires = time() + ($remember ? 30*86400 : 3600); // 30天 或 1小時
// 存資料庫:remember_tokens (selector, hashed_validator, user_id, expires)
saveRememberToken($selector, $hashedValidator, $user['id'], $expires);
// 設定 Cookie (HttpOnly 防 XSS)
setcookie('remember_token', $selector . ':' . $validator, [
'expires' => $expires,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
// 同時建立 Session
$_SESSION['user_id'] = $user['id'];
redirect('dashboard.php');
}
}
// auto_login.php (每次請求檢查)
if (empty($_SESSION['user_id']) && !empty($_COOKIE['remember_token'])) {
[$selector, $validator] = explode(':', $_COOKIE['remember_token'], 2);
$token = getRememberToken($selector); // 從 DB 查詢
if ($token && hash_equals($token['hashed_validator'], hash('sha256', $validator))) {
// 有效:建立 Session、更新過期時間、旋轉 Token
$_SESSION['user_id'] = $token['user_id'];
rotateRememberToken($selector);
} else {
// 無效:清除 Cookie
setcookie('remember_token', '', ['expires' => time()-3600, 'path'=>'/']);
}
}
?>
<?php
// 1. 查看發送的 Set-Cookie Header
header('X-Debug-Cookies: ' . implode('; ', array_map(fn($k,$v)=>"$k=$v", array_keys($_COOKIE), $_COOKIE)));
// 2. 瀏覽器 DevTools → Application → Cookies 檢查屬性
// 3. 測試工具
// curl -v -b "name=value" https://example.com/
// curl -v -c cookies.txt -b cookies.txt https://example.com/login.php
Cookie 操作核心原則:
Secure + HttpOnly + SameSite=Lax (預設)path、最小 domain、最短 expiresremember_token 簽名驗證)掌握這些,即能安全、合規地使用 Cookie 維持用戶狀態。