setcookie(string $name, string $value = "", int $expire = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false): bool
$expire 為 Unix 時間戳,0 或省略 = 瀏覽器關閉即失效(Session Cookie)。$path 預設為當前目錄,建議設 '/' 全站可用。$domain 設定可用網域(如 .example.com 含子網域)。$secure:true 僅 HTTPS 傳送。$httponly:true 禁止 JavaScript 存取(防 XSS 竊取)。<?php
// 建立:1 小時後過期,全站可用,僅 HTTPS+HttpOnly
setcookie('user_name', 'Alex', [
'expires' => time() + 3600,
'path' => '/',
'domain' => '.example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax', // PHP 7.3+ 防 CSRF
]);
// 讀取(下一次請求才會出現在 $_COOKIE)
if (isset($_COOKIE['user_name'])) {
echo "歡迎回來," . htmlspecialchars($_COOKIE['user_name']);
}
?>
注意:setcookie() 設定後,**當前請求的 $_COOKIE 不會立即更新**,需下一次請求才能讀取。
<?php
setcookie('prefs[theme]', 'dark', time()+3600, '/');
setcookie('prefs[lang]', 'zh-TW', time()+3600, '/');
setcookie('prefs[fontsize]', '16', time()+3600, '/');
// 讀取時 $_COOKIE['prefs'] 為陣列
if (isset($_COOKIE['prefs'])) {
foreach ($_COOKIE['prefs'] as $k => $v) {
echo "$k = " . htmlspecialchars($v) . "<br>";
}
}
?>
將過期時間設為**過去時間**(如 time() - 3600),值設為空字串:
<?php
function deleteCookie($name) {
setcookie($name, '', time() - 3600, '/', '.example.com', true, true);
}
deleteCookie('user_name');
deleteCookie('prefs[theme]');
?>
<?php
// config.php
define('SECRET_KEY', 'your_random_secret_key_here'); // 32+ 字元隨機字串
// login.php
session_start();
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
$remember = isset($_POST['remember']);
// 驗證帳密(此處略,實務查資料庫 password_verify)
$validUser = ($username === 'demo' && password_verify($password, '$2y$10$...'));
if ($validUser) {
$_SESSION['user_id'] = 123;
$_SESSION['username'] = $username;
if ($remember) {
// 產生簽名 token:username|expires|hmac
$expires = time() + 30*86400; // 30 天
$data = "$username|$expires";
$hash = hash_hmac('sha256', $data, SECRET_KEY);
$cookieValue = $data . '|' . $hash;
setcookie('auto_login', $cookieValue, [
'expires' => $expires,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
}
header('Location: dashboard.php');
exit;
} else {
$error = "帳號或密碼錯誤";
}
// auto_check.php(每頁頂端引入)
function checkAutoLogin() {
if (isset($_SESSION['user_id'])) return true; // 已登入
if (empty($_COOKIE['auto_login'])) return false;
$parts = explode('|', $_COOKIE['auto_login'], 3);
if (count($parts) !== 3) return false;
[$username, $expires, $hash] = $parts;
// 檢查過期
if ((int)$expires < time()) {
deleteCookie('auto_login');
return false;
}
// 驗證簽名
$data = "$username|$expires";
$expectedHash = hash_hmac('sha256', $data, SECRET_KEY);
if (!hash_equals($expectedHash, $hash)) {
deleteCookie('auto_login');
return false;
}
// 簽名驗證通過,自動登入(實務應再查資料庫確認用戶存在)
$_SESSION['user_id'] = getUserIdByName($username); // 自行實作
$_SESSION['username'] = $username;
return true;
}
?>