某些環境(如無寫入權限、容器化部署、高併發臨時會話)不適合使用 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"}}
若有多個 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');