You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP CURL中处理多个Set-Cookie响应头

解决PHP Curl无法捕获多个Set-Cookie响应头的问题

PHP Curl默认的头信息处理逻辑会合并多个Set-Cookie响应头,导致只能拿到合并后的结果或最后一个Cookie,解决核心是通过自定义响应头回调函数逐行捕获所有头信息,完整保留每个Set-Cookie条目。

具体实现方案

  1. 初始化Curl会话时,设置CURLOPT_HEADERFUNCTION回调,用于逐行处理响应头;
  2. 在回调函数中筛选出所有Set-Cookie开头的行,提取内容存入数组;
  3. 后续可直接使用数组中的Cookie,或拼接成标准格式用于后续请求。

代码示例

// 初始化Curl会话
$ch = curl_init('https://目标API地址/auth');
$capturedCookies = [];

// 设置头信息捕获回调
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $headerLine) use (&$capturedCookies) {
    $lineLength = strlen($headerLine);
    $trimmedHeader = trim($headerLine);
    
    // 匹配并提取Set-Cookie内容
    if (str_starts_with($trimmedHeader, 'Set-Cookie:')) {
        $cookieContent = substr($trimmedHeader, 11); // 移除"Set-Cookie: "前缀
        $capturedCookies[] = $cookieContent;
    }
    
    return $lineLength;
});

// 基础Curl配置
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 若需POST请求,添加对应配置
// curl_setopt($ch, CURLOPT_POST, true);
// curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($requestData));

// 执行请求
$responseBody = curl_exec($ch);
curl_close($ch);

// 输出所有捕获到的Cookie
print_r($capturedCookies);

后续请求携带Cookie

如果需要在后续接口请求中使用这些Cookie,可将数组拼接成标准Cookie格式:

$cookieString = implode('; ', $capturedCookies);

// 后续请求设置Cookie
$nextCh = curl_init('https://目标API地址/后续接口');
curl_setopt($nextCh, CURLOPT_COOKIE, $cookieString);
curl_setopt($nextCh, CURLOPT_RETURNTRANSFER, true);
$nextResponse = curl_exec($nextCh);
curl_close($nextCh);

原理说明

CURLOPT_HEADERFUNCTION会强制Curl将每一行响应头单独传递给回调函数,不会合并同类型的头字段,因此能完整捕获所有Set-Cookie条目,避开默认处理逻辑的局限性。

内容的提问来源于stack exchange,提问作者FileInputStream

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:07:16