萬盛學電腦網

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

PHP 與 JavaScript Cookie 設置、讀取、刪除完整實戰

PHP 端 Cookie 操作

設置 Cookie

<?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防護
]);
?>

讀取 Cookie

<?php
// 自動解析到 $_COOKIE 超全局數組
$value = $_COOKIE['cook'] ?? null;
if ($value !== null) {
    echo "Cookie 值: " . htmlspecialchars($value);
} else {
    echo "Cookie 不存在";
}
?>

刪除 Cookie

<?php
// 設置過期時間為過去
setcookie('cook', '', time() - 3600, '/');
// 或 PHP 7.3+
setcookie('cook', '', ['expires' => time() - 3600, 'path' => '/']);
?>

JavaScript 端 Cookie 操作 (原生 API)

封裝工具函數

<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 設置 → JS 讀取 → JS 修改 → PHP 驗證

1. PHP 設置初始 Cookie (set_cookie.php)

<?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 跨端演示

當前主題: 載入中...


    
    

2. JavaScript 邏輯 (demo.js)

// 讀取並應用主題
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;
    }
};

3. PHP 驗證 Token (verify_token.php)

<?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']]);
?>

安全最佳實踐總結

屬性推薦值說明
HttpOnlytrue防止 XSS 竊取敏感 Cookie (Session ID, Token)
Securetrue僅 HTTPS 傳輸,防中間人攻擊
SameSiteLax / StrictCSRF 防護,Lax 允許鏈接跳轉攜帶,Strict 完全禁止跨站攜帶
Domain最小必要域名避免父域名泄露,如 .example.com 而非 example.com
Path最小必要路徑限制 Cookie 發送範圍
Expires/Max-Age業務需要最小值減少暴露窗口

常見坑點

  • setcookie() 必須在 任何輸出之前調用 (包括空白字符、BOM)。
  • 域名設置:domain=.example.com 允許子域名共享,domain=example.com 僅當前域名 (現代瀏覽器行為一致,但規範建議加點)。
  • 同名 Cookie:路徑更具體的優先發送,PHP $_COOKIE 只取第一個,需自行解析 $_SERVER['HTTP_COOKIE'] 獲取所有。
  • 編碼:值含特殊字符必須 urlencode/encodeURIComponent,讀取時對應解碼。
copyright © 萬盛學電腦網 all rights reserved