首页 > 解决方案 > 从 curl 获取 cookie

问题描述

在 adobe connect api 中,获取数据有 2 个步骤:

步骤 1) 从http://87.107.152.107/api/xml?action=login&login=username&password=password我必须获取令牌以在其他 api 中进行验证。

第 2 步)http://87.107.152.107/api/xml?action=report-my-meetings我可以从第 1 步获得带有令牌的会议报告。

问题是当我使用邮递员使用这些 api 时,邮递员从步骤 1 api 设置 cookie。它需要此 cookie 用于第 2 步。

我想在 curl php 中使用 cookie,但我不知道如何获取它。我的第 1 步代码:

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'http://87.107.152.107/api/xml?action=login&login=username&password=password',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
    ));

    $response = curl_exec($curl);

标签: phpcurlcookies

解决方案


我使用它并为我工作:

    curl_setopt($ch, CURLOPT_HEADER, 1);
//Return everything
$res = curl_exec($ch);
//Split into lines
$lines = explode("\n", $res);
$headers = array();
$body = "";
foreach($lines as $num => $line){
    $l = str_replace("\r", "", $line);
    //Empty line indicates the start of the message body and end of headers
    if(trim($l) == ""){
        $headers = array_slice($lines, 0, $num);
        $body = $lines[$num + 1];
        //Pull only cookies out of the headers
        $cookies = preg_grep('/^Set-Cookie:/', $headers);
        break;
    }
}

推荐阅读