Cookie 由伺服器透過 HTTP 標頭 Set-Cookie 送至瀏覽器,瀏覽器後續請求會自動攜帶。PHP 自動將 Cookie 解析至 $_COOKIE 超全域陣列。
setcookie(
string $name,
string $value = '',
int $expire = 0,
string $path = '',
string $domain = '',
bool $secure = false,
bool $httponly = false
)
expire:Unix 時間戳,time()+3600 代表 1 小時後過期;0 為瀏覽器關閉失效。path:/ 表示全站有效;預設為當前腳本目錄。domain:.example.com 含所有子域名;www.example.com 僅限該主機。secure:僅 HTTPS 傳送。httponly:JavaScript 無法存取(防 XSS)。<?php
// 簡單設定
setcookie('lang', 'zh-TW', time() + 86400, '/'); // 1 天
// 完整參數(跨子域名、HTTPS、HttpOnly)
setcookie('auth_token', $token, time() + 3600, '/', '.example.com', true, true);
?>
<?php
// 單一值
$user = $_COOKIE['user'] ?? 'Guest';
// 檢查是否存在
if (isset($_COOKIE['remember_me'])) {
// 自動登入邏輯
}
// 除錯:查看所有 Cookie
print_r($_COOKIE);
// 必須與設定時相同的 path、domain、secure、httponly
setcookie('auth_token', '', time() - 3600, '/', '.example.com', true, true);
function setLoginCookie($userId, $username, $role, $ip, $expire = 86400) {
$domain = '.example.com'; // 依實際域名調整
$secure = true; // 僅 HTTPS
$httponly = true; // 防 XSS
// 加密敏感資料(示意,實務請用 openssl 或 sodium)
$payload = "$userId|$username|$role|$ip";
$encrypted = base64_encode(openssl_encrypt($payload, 'AES-256-CBC', ENCRYPT_KEY, 0, IV));
setcookie('uid', $userId, time() + $expire, '/', $domain, $secure, $httponly);
setcookie('uname', $username, time() + $expire, '/', $domain, $secure, $httponly);
setcookie('urole', $role, time() + $expire, '/', $domain, $secure, $httponly);
setcookie('usec', $encrypted, time() + $expire, '/', $domain, $secure, $httponly);
}
function validateLoginCookie() {
if (!isset($_COOKIE['uid'], $_COOKIE['usec'])) return false;
$decrypted = openssl_decrypt(base64_decode($_COOKIE['usec']), 'AES-256-CBC', ENCRYPT_KEY, 0, IV);
[$uid, $uname, $role, $ip] = explode('|', $decrypted);
// 驗證 IP、角色等
if ($ip !== $_SERVER['REMOTE_ADDR']) return false;
return ['uid' => $uid, 'username' => $uname, 'role' => $role];
}
setcookie(..., ['samesite' => 'Lax']) 防禦 CSRF。$_COOKIE 只包含請求時瀏覽器送來的 Cookie,剛 setcookie() 設定的需下一次請求才會出現。解決:同步寫入 $_COOKIE[$name] = $value(如本文前文 set_cookie_live 函數)。setcookie 會自動 URL 編碼,讀取時自動解碼,但建議自行 urlencode/urldecode 確保一致性。Cookie 是無狀態 HTTP 的關鍵狀態載體,正確設定屬性、加密敏感資料、配合 SameSite/HttpOnly/Secure 三大旗標,能構建安全可靠的用戶識別機制。