萬盛學電腦網

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

PHP cURL 實現 Cookie 會話保持與自動登錄完整指南

cURL 的 Cookie 機制是模擬瀏覽器會話、實現自動登錄、爬蟲維持狀態的核心技能。本文詳解 CURLOPT_COOKIEJAR/CURLOPT_COOKIEFILE 雙刀流、Cookie 文件格式解析、多執行緒安全、Session 生命週期管理。

核心選項速查

選項作用典型值
CURLOPT_COOKIEJAR響應 Cookie 寫入文件 (更新)/tmp/cookies.txt
CURLOPT_COOKIEFILE請求攜帶 Cookie 讀取文件/tmp/cookies.txt (同 JAR 實現持久化)
CURLOPT_COOKIE直接設置請求 Cookie 字符串"PHPSESSID=abc; user=john"
CURLOPT_COOKIESESSIONtrue: 忽略 session cookie (啟動新會話)true/false

完整登錄流程實現

<?php
class CurlSession {
    private string $cookieFile;
    private resource $ch;
    
    public function __construct(string $cookieFile = '') {
        $this->cookieFile = $cookieFile ?: sys_get_temp_dir() . '/curl_cookie_' . spl_object_id($this) . '.txt';
        $this->ch = curl_init();
        $this->setupDefaults();
    }
    
    private function setupDefaults(): void {
        curl_setopt_array($this->ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_SSL_VERIFYPEER => false,  // 開發環境;生產必須驗證
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            CURLOPT_COOKIEJAR => $this->cookieFile,
            CURLOPT_COOKIEFILE => $this->cookieFile,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 10,
        ]);
    }
    
    /** 執行 POST 登錄 */
    public function login(string $url, array $credentials): bool {
        curl_setopt_array($this->ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($credentials),
            CURLOPT_REFERER => $url,
        ]);
        
        $response = curl_exec($this->ch);
        if ($response === false) {
            throw new \RuntimeException('cURL 錯誤: ' . curl_error($this->ch));
        }
        
        // 檢查登錄成功標誌 (根據目標站點調整)
        $httpCode = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
        $setCookie = curl_getinfo($this->ch, CURLINFO_COOKIELIST);
        
        return $httpCode === 200 && (str_contains($response, '登錄成功') || !empty($setCookie));
    }
    
    /** 攜帶 Cookie 訪問受保護頁面 */
    public function get(string $url): string {
        curl_setopt($this->ch, CURLOPT_URL, $url);
        curl_setopt($this->ch, CURLOPT_HTTPGET, true);
        return curl_exec($this->ch) ?: throw new \RuntimeException(curl_error($this->ch));
    }
    
    /** 獲取當前所有 Cookie (解析 Netscape 格式) */
    public function getCookies(): array {
        $cookies = [];
        if (file_exists($this->cookieFile)) {
            $lines = file($this->cookieFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($lines as $line) {
                if (str_starts_with($line, '#')) continue;  // 註釋行
                [$domain, $flag, $path, $secure, $expires, $name, $value] = explode("\t", $line);
                $cookies[$name] = [
                    'value' => $value,
                    'domain' => $domain,
                    'path' => $path,
                    'secure' => (bool)$secure,
                    'expires' => $expires ? (int)$expires : null,
                    'httponly' => $flag === 'TRUE',
                ];
            }
        }
        return $cookies;
    }
    
    /** 清理會話 */
    public function destroy(): void {
        curl_close($this->ch);
        if (file_exists($this->cookieFile)) @unlink($this->cookieFile);
    }
    
    public function __destruct() {
        $this->destroy();
    }
}

// 使用示例
$session = new CurlSession();
$loggedIn = $session->login('https://example.com/login', [
    'username' => 'admin',
    'password' => 'secret123',
    'csrf_token' => '...',  // 可能需先 GET 登錄頁獲取 CSRF
]);

if ($loggedIn) {
    $dashboard = $session->get('https://example.com/dashboard');
    echo $dashboard;
    
    // 調試 Cookie
    print_r($session->getCookies());
}

Netscape Cookie 文件格式解析

# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# 這是一個註釋行

# 域名		尾匹配	路徑	安全	過期	名稱	值
.example.com	TRUE	/	FALSE	1735689600	PHPSESSID	abc123def456
secure.example.com	FALSE	/admin	TRUE	0	admin_token	xyz789
# TRUE/TRUE: 所有子域匹配/僅精確域名
# TRUE/FALSE: 僅 HTTPS/HTTP+HTTPS
# 0 = Session Cookie (瀏覽器關閉失效)
# Unix 時間戳 = 絕對過期時間

多執行緒/進程安全問題

痛點:文件鎖競爭、讀寫衝突、Cookie 丟失。

解決方案

  1. 進程隔離:每進程/協程獨立 Cookie 文件 (spl_object_id()、posix_getpid()、UUID)
  2. 內存 Cookie 罐:不落地文件,用陣列管理
    $cookieJar = [];
    function parseSetCookie(string $header): void {
        // 解析 Set-Cookie 頭更新 $cookieJar
    }
    function buildCookieHeader(): string {
        return implode('; ', array_map(fn($k,$v)=>"$k=$v", array_keys($cookieJar), $cookieJar));
    }
  3. Redis 共享 Cookie 池:Key: curl:cookie:{session_id},Value: JSON 序列化 Cookie 陣列,TTL 同步過期時間

高級場景:CSRF Token 自動提取與攜帶

<?php
function extractCsrfToken(string $html): ?string {
    // Meta 標籤
    if (preg_match('/]*name=["\']_token["\'][^>]*value=["\']([^"\']+)["\']/i', $html, $m)) {
        return $m[1];
    }
    // JavaScript 變量
    if (preg_match('/csrfToken\s*[:=]\s*["\']([^"\']+)["\']/', $html, $m)) {
        return $m[1];
    }
    return null;
}

// 登錄流程增強
$loginPage = $session->get('https://example.com/login');
$csrf = extractCsrfToken($loginPage);
$credentials['_token'] = $csrf ?? '';
$session->login('https://example.com/login', $credentials);

總結

cURL Cookie 管理核心:**雙刀流 (COOKIEJAR + COOKIEFILE) 實現持久化、Netscape 格式解析、進程隔離避免衝突、CSRF 自動提取**。封裝為可復用類,配合異常處理、超時控制、User-Agent 偽裝,構建健壯的 HTTP 會話客戶端。

copyright © 萬盛學電腦網 all rights reserved