萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP setcookie() Cookie 設定、讀取、刪除與自動登入完整指南

基本語法

setcookie(string $name, string $value = "", int $expire = 0, string $path = "", string $domain = "", bool $secure = false, bool $httponly = false): bool
  • 必須在任何輸出之前呼叫(含空白、HTML、BOM)。
  • $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 不會立即更新**,需下一次請求才能讀取。

儲存陣列資料(自動序列化為多個 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>";
    }
}
?>

刪除 Cookie

將過期時間設為**過去時間**(如 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;
}
?>

安全性最佳實踐

  1. HttpOnly + Secure + SameSite:預防 XSS 與 CSRF。
  2. 敏感資料勿存 Cookie:密碼、Token、個資請存在 Server 端 Session/資料庫。
  3. 簽名驗證:自動登入 Cookie 必須簽名(HMAC),防止竄改。
  4. 定期輪換 Secret Key:並提供「登出所有裝置」功能。
  5. 設定路徑/網域最小化:避免洩漏給不需存取的子系統。
copyright © 萬盛學電腦網 all rights reserved