首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

cURL 不寫入文件獲取與使用 Cookie 的 PHP 示例

     編輯:PHP 相關知識

場景

某些環境(如無寫入權限、容器化部署、高併發臨時會話)不適合使用 CURLOPT_COOKIEJAR/CURLOPT_COOKIEFILE 文件存儲 Cookie。可在內存中直接提取、攜帶 Cookie 字符串。

核心代碼

<?php
/*----- 步驟 1:登錄獲取 Cookie -----*/
$url = 'https://example.com/login';
$post = "username=user&password=123456";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);           // 輸出頭部以獲取 Set-Cookie
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   // 返回字符串
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 測試環境忽略證書
$content = curl_exec($ch);

// 正則提取 Set-Cookie(可能有多個,取第一個或拼接)
preg_match('/Set-Cookie:\s*([^;]+)/i', $content, $matches);
$cookie = $matches[1] ?? ''; // 例:PHPSESSID=abc123
curl_close($ch);

if (!$cookie) die('登錄失敗,未獲取到 Cookie');

/*----- 步驟 2:攜帶 Cookie 訪問受保護資源 -----*/
$apiUrl = 'https://example.com/api/user/info';
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIE, $cookie); // 直接設置 Cookie 字符串
$response = curl_exec($ch);
curl_close($ch);

echo $response; // {"code":0,"data":{"name":"user"}}

進階:處理多個 Cookie

若有多個 Set-Cookie 頭,需全部提取並以分號拼接:

preg_match_all('/Set-Cookie:\s*([^;]+)/i', $content, $matches);
$cookie = implode('; ', $matches[1]); // PHPSESSID=abc; token=xyz

封裝為可復用類

<?php
class CurlCookieClient {
    private $ch;
    private $cookie = '';

    public function __construct() {
        $this->ch = curl_init();
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
    }

    public function post($url, $data) {
        curl_setopt($this->ch, CURLOPT_URL, $url);
        curl_setopt($this->ch, CURLOPT_POST, 1);
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($this->ch, CURLOPT_HEADER, 1);
        $content = curl_exec($this->ch);
        $this->extractCookie($content);
        return $this->stripHeader($content);
    }

    public function get($url) {
        curl_setopt($this->ch, CURLOPT_URL, $url);
        curl_setopt($this->ch, CURLOPT_POST, 0);
        curl_setopt($this->ch, CURLOPT_HEADER, 0);
        if ($this->cookie) {
            curl_setopt($this->ch, CURLOPT_COOKIE, $this->cookie);
        }
        return curl_exec($this->ch);
    }

    private function extractCookie($header) {
        preg_match_all('/Set-Cookie:\s*([^;]+)/i', $header, $m);
        if ($m[1]) $this->cookie = implode('; ', $m[1]);
    }

    private function stripHeader($response) {
        list($header, $body) = explode("\r\n\r\n", $response, 2);
        return $body;
    }

    public function __destruct() {
        curl_close($this->ch);
    }
}

// 使用
$client = new CurlCookieClient();
$client->post('https://example.com/login', ['user'=>'a','pass'=>'1']);
echo $client->get('https://example.com/api/profile');

注意事項

  • 安全性:Cookie 含敏感標識,內存中處理避免文件洩露,但進程內存轉儲仍可讀取,權衡場景使用。
  • 有效期:Session Cookie 瀏覽器關閉即失效,服務端可能設置較短 TTL,需適時重新登錄。
  • 並發:同一實例不支持並發請求(共享 Cookie 狀態),多線程/協程場景請各自實例化。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved