Cookie 是伺服器儲存在客戶端的小型文字資料,常用於識別用戶、記住偏好設定、追蹤行為等場景。PHP 提供直觀的函數操作 Cookie,本文涵蓋完整生命週期管理與實務技巧。
必須在任何輸出之前呼叫(同 session_start())。
setcookie(name, value, expire, path, domain, secure, httponly);
| 參數 | 說明 |
|---|---|
| name | Cookie 名稱(陣列鍵名) |
| value | 儲存值,自動 URL 編碼 |
| expire | 過期 Unix 時間戳,0 或省略為會話結束 |
| path | 生效路徑,'/' 表示全域名 |
| domain | 生效域名,'.example.com' 包含子域名 |
| secure | true 僅 HTTPS 傳輸 |
| httponly | true 禁止 JavaScript 存取 |
<?php
setcookie("user", "runoob", time() + 3600);
?>
<html>...</html>
<?php
$expire = time() + 60 * 60 * 24 * 30; // 30天
setcookie("user", "runoob", $expire, "/", "", true, true);
// 路徑 域名 HTTPS HttpOnly
?>
提示:若不想自動 URL 編碼,可使用 setrawcookie()。
PHP 自動解碼並填入超全域陣列 $_COOKIE。
<?php
// 讀取特定 Cookie
if (isset($_COOKIE["user"])) {
echo "歡迎回來," . htmlspecialchars($_COOKIE["user"]) . "!";
} else {
echo "你好,訪客!";
}
// 檢視所有 Cookie
print_r($_COOKIE);
?>
安全提醒:輸出 Cookie 值時務必使用 htmlspecialchars() 防止 XSS。
將過期時間設為過去時間點即可:
<?php
// 刪除 user cookie
setcookie("user", "", time() - 3600, "/");
// 路徑必須與建立時一致才能生效
?>
部分用戶禁用 Cookie 或使用隱私模式,需備用方案:
<form action="process.php" method="post">
<input type="hidden" name="session_id" value="<?php echo session_id(); ?>">
<!-- 其他欄位 -->
</form>
啟用 session.use_trans_sid = 1(php.ini)或編譯時加入 --enable-trans-sid,PHP 會自動在連結中附加 Session ID。注意:有安全風險(URL 可能被分享、記錄在日誌中),謹慎使用。
現代瀏覽器支援更大容量的客戶端儲存,配合 AJAX 傳送資料至伺服器,適合非敏感偏好設定。
<?php
class CookieManager {
private $defaultPath = '/';
private $defaultDomain = '';
private $secure = true;
private $httponly = true;
public function set($name, $value, $expire = 0, $path = null, $domain = null) {
return setcookie(
$name, $value,
$expire ? time() + $expire : 0,
$path ?? $this->defaultPath,
$domain ?? $this->defaultDomain,
$this->secure,
$this->httponly
);
}
public function get($name, $default = null) {
return $_COOKIE[$name] ?? $default;
}
public function delete($name, $path = null, $domain = null) {
return setcookie(
$name, '',
time() - 3600,
$path ?? $this->defaultPath,
$domain ?? $this->defaultDomain,
$this->secure,
$this->httponly
);
}
// 批次設定:記住我功能
public function rememberMe($userId, $token, $days = 30) {
$this->set('remember_user', $userId, 86400 * $days);
$this->set('remember_token', $token, 86400 * $days);
}
public function clearRememberMe() {
$this->delete('remember_user');
$this->delete('remember_token');
}
}
?>
PHPSESSID Cookie 識別伺服器端 SessionHttpOnly、SecurePath 與 Domain 限制範圍Cookie 雖簡單,但關鍵在於「最小權限原則」:只在必要範圍、必要時間、必要安全層級下使用。配合 Session 機制,能構建流暢且安全的用戶體驗。