<?php
class CookieManager {
private string $secretKey;
private string $domain;
private bool $secure;
public function __construct(string $secretKey, string $domain = '', bool $secure = true) {
$this->secretKey = $secretKey;
$this->domain = $domain;
$this->secure = $secure;
}
/**
* 設定 Cookie(可選加密)
*/
public function set(string $name, string $value, int $expire = 2592000, bool $encrypt = true): void {
if ($encrypt) {
$value = $this->encrypt($value);
}
$options = [
'expires' => time() + $expire,
'path' => '/',
'domain' => $this->domain ?: '',
'secure' => $this->secure,
'httponly' => true,
'samesite' => 'Lax',
];
setcookie($name, $value, $options);
}
/**
* 讀取 Cookie(自動解密)
*/
public function get(string $name, bool $decrypt = true): ?string {
$value = $_COOKIE[$name] ?? null;
if ($value === null) return null;
return $decrypt ? $this->decrypt($value) : $value;
}
/**
* 刪除 Cookie
*/
public function delete(string $name): void {
$options = [
'expires' => time() - 3600,
'path' => '/',
'domain' => $this->domain ?: '',
'secure' => $this->secure,
'httponly' => true,
'samesite' => 'Lax',
];
setcookie($name, '', $options);
}
private function encrypt(string $data): string {
$iv = random_bytes(16);
$cipher = openssl_encrypt($data, 'AES-256-CBC', $this->secretKey, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $cipher);
}
private function decrypt(string $data): string {
$raw = base64_decode($data);
$iv = substr($raw, 0, 16);
$cipher = substr($raw, 16);
return openssl_decrypt($cipher, 'AES-256-CBC', $this->secretKey, OPENSSL_RAW_DATA, $iv);
}
}
// 使用範例
$cookie = new CookieManager('your-32-char-secret-key-here!!!', '.example.com');
$cookie->set('user_id', '12345', 86400); // 1 天
$userId = $cookie->get('user_id');
$cookie->delete('user_id');
function w_cookie(string $name, string $value, int $expireDays = 30, bool $encrypt = true): void {
$expire = $expireDays === 0 ? 0 : time() + $expireDays * 86400;
if ($encrypt) {
// 這裡需實作加密,略...
}
setcookie($name, $value, $expire, '/', '', true, true); // secure, httponly
}
// 刪除:expire 設為過去時間
w_cookie('bb', '', -1);
| 參數 | 說明 | 建議值 |
|---|---|---|
| expires | 過期時間戳,0=瀏覽器關閉失效 | 86400~2592000 |
| path | Cookie 生效路徑 | / |
| domain | 共用父域設 .example.com | 視架構而定 |
| secure | 僅 HTTPS 傳送 | true(生產必開) |
| httponly | JS 無法讀取,防 XSS | true |
| samesite | 跨站傳送策略 | Lax / None(需Secure) |
domain=.example.com(前綴點號)原始來源:www.111cn.net