<?php
// 基礎設置:名稱、值、過期時間(Unix時間戳)、路徑、域名、Secure、HttpOnly
$value = 'oicq';
$expire = time() + 7200; // 2小時
$path = '/';
$domain = ''; // 當前域名
$secure = true; // 僅HTTPS
$httponly = true; // 防XSS
setcookie('cook', $value, $expire, $path, $domain, $secure, $httponly);
// 簡寫 (PHP 7.3+ 支援選項數組)
setcookie('cook', $value, [
'expires' => $expire,
'path' => $path,
'domain' => $domain,
'secure' => $secure,
'httponly' => $httponly,
'samesite' => 'Lax' // CSRF防護
]);
?>
<?php
// 自動解析到 $_COOKIE 超全局數組
$value = $_COOKIE['cook'] ?? null;
if ($value !== null) {
echo "Cookie 值: " . htmlspecialchars($value);
} else {
echo "Cookie 不存在";
}
?>
<?php
// 設置過期時間為過去
setcookie('cook', '', time() - 3600, '/');
// 或 PHP 7.3+
setcookie('cook', '', ['expires' => time() - 3600, 'path' => '/']);
?>
<script>
const CookieUtil = {
// 設置
set(name, value, options = {}) {
let cookieStr = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
if (options.expires instanceof Date) {
cookieStr += `;expires=${options.expires.toUTCString()}`;
} else if (typeof options.expires === 'number') {
// 假設為秒
const d = new Date();
d.setTime(d.getTime() + options.expires * 1000);
cookieStr += `;expires=${d.toUTCString()}`;
}
if (options.path) cookieStr += `;path=${options.path}`;
if (options.domain) cookieStr += `;domain=${options.domain}`;
if (options.secure) cookieStr += ';secure';
if (options.sameSite) cookieStr += `;samesite=${options.sameSite}`;
document.cookie = cookieStr;
},
// 讀取
get(name) {
const match = document.cookie.match(new RegExp('(^|;\\s*)' + encodeURIComponent(name) + '=([^;]*)'));
return match ? decodeURIComponent(match[2]) : null;
},
// 刪除
remove(name, options = {}) {
this.set(name, '', { ...options, expires: new Date(0) });
},
// 獲取所有
all() {
return document.cookie.split(';').reduce((acc, item) => {
const [k, v] = item.trim().split('=');
acc[decodeURIComponent(k)] = decodeURIComponent(v);
return acc;
}, {});
}
};
// 使用示例
CookieUtil.set('theme', 'dark', { expires: 3600, path: '/', sameSite: 'Lax' });
console.log(CookieUtil.get('theme')); // 'dark'
CookieUtil.remove('theme', { path: '/' });
</script>
<?php
// 設置一個帶簽名的 Cookie,防止客戶端篡改
$secret = 'your_secret_key_here';
$userId = 12345;
$expire = time() + 86400; // 1天
$payload = json_encode(['uid' => $userId, 'exp' => $expire]);
$signature = hash_hmac('sha256', $payload, $secret);
$cookieValue = base64_encode($payload . '.' . $signature);
setcookie('auth_token', $cookieValue, [
'expires' => $expire,
'path' => '/',
'httponly' => true, // JS 無法讀取,安全
'secure' => true,
'samesite' => 'Lax'
]);
// 同時設置一個 JS 可讀的偏好設置 Cookie
setcookie('ui_theme', 'light', [
'expires' => time() + 3600*24*30,
'path' => '/',
'samesite' => 'Lax'
]);
?>
Cookie Demo
Cookie 跨端演示
當前主題: 載入中...
// 讀取並應用主題
const theme = CookieUtil.get('ui_theme') || 'light';
document.body.className = `theme-${theme}`;
document.getElementById('theme-display').textContent = theme;
document.getElementById('toggle-theme').onclick = () => {
const newTheme = theme === 'dark' ? 'light' : 'dark';
CookieUtil.set('ui_theme', newTheme, { expires: 3600*24*30, path: '/', sameSite: 'Lax' });
document.body.className = `theme-${newTheme}`;
document.getElementById('theme-display').textContent = newTheme;
};
// 驗證 PHP 端 HttpOnly Cookie (需 AJAX 請求)
document.getElementById('verify-php').onclick = async () => {
try {
const res = await fetch('verify_token.php', { credentials: 'include' });
const data = await res.json();
document.getElementById('output').textContent = JSON.stringify(data, null, 2);
} catch (e) {
document.getElementById('output').textContent = '錯誤: ' + e.message;
}
};
<?php
header('Content-Type: application/json');
$secret = 'your_secret_key_here';
$cookie = $_COOKIE['auth_token'] ?? '';
if (!$cookie) {
http_response_code(401);
echo json_encode(['valid' => false, 'error' => 'Token 缺失']);
exit;
}
$data = base64_decode($cookie);
[$payload, $signature] = explode('.', $data, 2);
$expectedSig = hash_hmac('sha256', $payload, $secret);
if (!hash_equals($expectedSig, $signature)) {
http_response_code(403);
echo json_encode(['valid' => false, 'error' => '簽名驗證失敗']);
exit;
}
$payload = json_decode($payload, true);
if ($payload['exp'] < time()) {
http_response_code(401);
echo json_encode(['valid' => false, 'error' => 'Token 過期']);
exit;
}
echo json_encode(['valid' => true, 'user_id' => $payload['uid']]);
?>
| 屬性 | 推薦值 | 說明 |
|---|---|---|
| HttpOnly | true | 防止 XSS 竊取敏感 Cookie (Session ID, Token) |
| Secure | true | 僅 HTTPS 傳輸,防中間人攻擊 |
| SameSite | Lax / Strict | CSRF 防護,Lax 允許鏈接跳轉攜帶,Strict 完全禁止跨站攜帶 |
| Domain | 最小必要域名 | 避免父域名泄露,如 .example.com 而非 example.com |
| Path | 最小必要路徑 | 限制 Cookie 發送範圍 |
| Expires/Max-Age | 業務需要最小值 | 減少暴露窗口 |
setcookie() 必須在 任何輸出之前調用 (包括空白字符、BOM)。domain=.example.com 允許子域名共享,domain=example.com 僅當前域名 (現代瀏覽器行為一致,但規範建議加點)。$_COOKIE 只取第一個,需自行解析 $_SERVER['HTTP_COOKIE'] 獲取所有。urlencode/encodeURIComponent,讀取時對應解碼。