萬盛學電腦網

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

PHP cURL 不寫檔案管理 Cookie:記憶體中解析與攜帶 Cookie 完整實作

為什麼不想用 COOKIEJAR/COOKIEFILE?

  • 無檔案系統寫入權限(Serverless、唯讀容器、共享主機)
  • 多進程/協程併發時檔案鎖衝突
  • 臨時會話不需持久化,進程結束即銷毀
  • 安全考量:避免 Cookie 洩漏到磁碟

核心原理:手動解析 Set-Cookie → 記憶體陣列 → 重組 Cookie 標頭

<?php
class MemoryCookieJar
{
    /** @var array */
    private array $cookies = [];
    
    private string $defaultDomain = '';
    private string $defaultPath = '/';

    /** 從 Set-Cookie 標頭解析並儲存 */
    public function parseSetCookie(string $setCookieHeader, string $requestUrl): void
    {
        // 解析單個 Set-Cookie(可能有多個,由 header 陣列傳入)
        $parts = explode(';', $setCookieHeader);
        $nameValue = trim(array_shift($parts));
        [$name, $value] = array_pad(explode('=', $nameValue, 2), 2, '');
        
        $cookie = [
            'value' => urldecode($value),
            'domain' => $this->defaultDomain,
            'path' => $this->defaultPath,
            'expires' => null,
            'secure' => false,
            'httponly' => false,
            'samesite' => 'Lax',
        ];

        foreach ($parts as $part) {
            $part = trim($part);
            if (stripos($part, 'domain=') === 0) {
                $cookie['domain'] = substr($part, 7);
            } elseif (stripos($part, 'path=') === 0) {
                $cookie['path'] = substr($part, 5);
            } elseif (stripos($part, 'expires=') === 0) {
                $cookie['expires'] = strtotime(substr($part, 8));
            } elseif (stripos($part, 'max-age=') === 0) {
                $cookie['expires'] = time() + (int)substr($part, 8);
            } elseif (strcasecmp($part, 'secure') === 0) {
                $cookie['secure'] = true;
            } elseif (strcasecmp($part, 'httponly') === 0) {
                $cookie['httponly'] = true;
            } elseif (stripos($part, 'samesite=') === 0) {
                $cookie['samesite'] = ucfirst(strtolower(substr($part, 9)));
            }
        }

        // 修正 domain:移除前導點、驗證尾部匹配
        $cookie['domain'] = ltrim($cookie['domain'], '.');
        $urlHost = parse_url($requestUrl, PHP_URL_HOST);
        if ($urlHost && !$this->domainMatch($urlHost, $cookie['domain'])) {
            // 域名不匹配,拒絕設定(安全策略)
            return;
        }

        $this->cookies[$name] = $cookie;
    }

    /** 域名匹配:cookie domain 必須是請求域名的尾部匹配 */
    private function domainMatch(string $requestHost, string $cookieDomain): bool
    {
        if ($cookieDomain === '') return true;
        $requestHost = strtolower($requestHost);
        $cookieDomain = strtolower($cookieDomain);
        return $requestHost === $cookieDomain || 
               (str_ends_with($requestHost, '.' . $cookieDomain) && 
                substr_count($cookieDomain, '.') >= 1); // 至少有一個點,防止 .com 等公共後綴
    }

    /** 為指定 URL 生成 Cookie 請求標頭 */
    public function getCookieHeader(string $url): string
    {
        $host = parse_url($url, PHP_URL_HOST) ?? '';
        $path = parse_url($url, PHP_URL_PATH) ?? '/';
        $isSecure = (parse_url($url, PHP_URL_SCHEME) ?? '') === 'https';
        $now = time();

        $applicable = [];
        foreach ($this->cookies as $name => $cookie) {
            // 過期檢查
            if ($cookie['expires'] !== null && $cookie['expires'] < $now) {
                unset($this->cookies[$name]);
                continue;
            }
            // Secure 檢查
            if ($cookie['secure'] && !$isSecure) continue;
            // Domain 匹配
            if (!$this->domainMatch($host, $cookie['domain'])) continue;
            // Path 匹配
            if (!str_starts_with($path, $cookie['path'])) continue;
            
            $applicable[$name] = $cookie['value'];
        }

        return implode('; ', array_map(fn($n, $v) => "$n=$v", array_keys($applicable), $applicable));
    }

    /** 獲取特定 Cookie 值 */
    public function get(string $name): ?string
    {
        return $this->cookies[$name]['value'] ?? null;
    }

    /** 清除所有/特定 Cookie */
    public function clear(?string $name = null): void
    {
        if ($name) unset($this->cookies[$name]);
        else $this->cookies = [];
    }

    /** 導出陣列(用於序列化/除錯) */
    public function toArray(): array
    {
        return $this->cookies;
    }
}
?>

整合 cURL 使用流程

<?php
function curlWithMemoryCookie(string $url, array $options = []): array
{
    $cookieJar = new MemoryCookieJar();
    $ch = curl_init($url);
    
    // 關鍵:啟用標頭輸出以捕獲 Set-Cookie
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt_array($ch, $options);
    
    $response = curl_exec($ch);
    if ($response === false) {
        throw new RuntimeException('cURL error: ' . curl_error($ch));
    }
    
    // 分離標頭與主體
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $headers = substr($response, 0, $headerSize);
    $body = substr($response, $headerSize);
    
    // 解析所有 Set-Cookie
    $headerLines = explode("\r\n", $headers);
    foreach ($headerLines as $line) {
        if (stripos($line, 'Set-Cookie:') === 0) {
            $cookieLine = substr($line, 11); // 去掉 "Set-Cookie: "
            $cookieJar->parseSetCookie($cookieLine, $url);
        }
    }
    
    curl_close($ch);
    
    return [
        'body' => $body,
        'headers' => $headers,
        'cookies' => $cookieJar->toArray(),
        'cookie_header' => $cookieJar->getCookieHeader($url), // 供下次請求使用
    ];
}

// 使用範例:模擬登入流程
$jar = new MemoryCookieJar();

// 1. 訪問登入頁(獲取 CSRF token、建立 session)
$loginPage = curlWithMemoryCookie('https://example.com/login', [
    CURLOPT_USERAGENT => 'Mozilla/5.0...',
]);
$csrfToken = extractCsrfToken($loginPage['body']);

// 2. 提交登入表單(攜帶上一步獲得的 Cookie)
$loginResult = curlWithMemoryCookie('https://example.com/login', [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query([
        '_token' => $csrfToken,
        'email' => 'user@example.com',
        'password' => 'secret',
    ]),
    CURLOPT_COOKIE => $jar->getCookieHeader('https://example.com/login'), // 手動注入
    CURLOPT_REFERER => 'https://example.com/login',
]);

// 3. 解析登入回應的 Set-Cookie,更新 Jar
foreach (explode("\r\n", $loginResult['headers']) as $line) {
    if (stripos($line, 'Set-Cookie:') === 0) {
        $jar->parseSetCookie(substr($line, 11), 'https://example.com/login');
    }
}

// 4. 訪問受保護頁面(攜帶完整 Cookie)
$dashboard = curlWithMemoryCookie('https://example.com/dashboard', [
    CURLOPT_COOKIE => $jar->getCookieHeader('https://example.com/dashboard'),
]);
?>

進階:支援多域名、自動重定向 Cookie 追蹤

<?php
class AutoCookieCurl
{
    private MemoryCookieJar $jar;
    private resource $ch;
    
    public function __construct()
    {
        $this->jar = new MemoryCookieJar();
        $this->ch = curl_init();
        curl_setopt_array($this->ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_AUTOREFERER => true,
            CURLOPT_SSL_VERIFYPEER => true,
        ]);
    }
    
    public function request(string $url, array $options = []): array
    {
        // 合併預設 Cookie
        $options[CURLOPT_COOKIE] = ($options[CURLOPT_COOKIE] ?? '') 
            . ($options[CURLOPT_COOKIE] ? '; ' : '') 
            . $this->jar->getCookieHeader($url);
        
        curl_setopt_array($this->ch, $options + [CURLOPT_URL => $url]);
        $response = curl_exec($this->ch);
        
        // 解析回應標頭中的 Set-Cookie(包含重定向鏈)
        $headerSize = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE);
        $headers = substr($response, 0, $headerSize);
        $this->parseAllSetCookies($headers, $url);
        
        return [
            'body' => substr($response, $headerSize),
            'http_code' => curl_getinfo($this->ch, CURLINFO_HTTP_CODE),
            'effective_url' => curl_getinfo($this->ch, CURLINFO_EFFECTIVE_URL),
        ];
    }
    
    private function parseAllSetCookies(string $headers, string $baseUrl): void
    {
        // 處理多行 Set-Cookie,包含重定向產生的
        preg_match_all('/^Set-Cookie:\s*(.+)$/mi', $headers, $matches);
        foreach ($matches[1] as $cookieLine) {
            // 使用有效 URL(重定向後的最終 URL)作為域名匹配基準
            $effectiveUrl = curl_getinfo($this->ch, CURLINFO_EFFECTIVE_URL);
            $this->jar->parseSetCookie($cookieLine, $effectiveUrl);
        }
    }
    
    public function getCookieJar(): MemoryCookieJar
    {
        return $this->jar;
    }
    
    public function __destruct()
    {
        curl_close($this->ch);
    }
}
?>

序列化持久化(跨請求/進程共享)

<?php
// 儲存到 Redis/Session/資料庫
$serialized = serialize($cookieJar->toArray());
// 或 JSON(需處理資源類型)
$json = json_encode($cookieJar->toArray());

// 還原
$jar = new MemoryCookieJar();
foreach (json_decode($json, true) as $name => $data) {
    $jar->cookies[$name] = $data;
}
?>

總結

不使用檔案管理 Cookie 的核心是:手動解析 Set-Cookie 標頭 → 記憶體結構化儲存 → 請求時重組 Cookie 標頭。上述 MemoryCookieJar 類別完整實現了 RFC 6265 核心邏輯(Domain/Path/Secure/HttpOnly/Expires/SameSite 匹配),可直接用於 Serverless、容器化、高併發場景。若需跨進程共享,配合 Redis 序列化即可。

copyright © 萬盛學電腦網 all rights reserved