萬盛學電腦網

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

PHP Cookie 設定與刪除完整封裝:加密、有效期、路徑、域、SameSite、HttpOnly

完整 Cookie 封裝類別

<?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
pathCookie 生效路徑/
domain共用父域設 .example.com視架構而定
secure僅 HTTPS 傳送true(生產必開)
httponlyJS 無法讀取,防 XSStrue
samesite跨站傳送策略Lax / None(需Secure)

常見錯誤

  • 刪除 Cookie 必須**完全相同的 path/domain/secure/samesite** 參數
  • 加密金鑰需 ≥ 32 字元(AES-256)
  • 不要在 Cookie 儲存敏感資料(Token、權限),改用 Session + CSRF Token
  • 子域共用需 domain=.example.com(前綴點號)

原始來源:www.111cn.net

copyright © 萬盛學電腦網 all rights reserved