Organizational Research By

Surprising Reserch Topic

get the cookies from a php curl into a variable



asked May 28, 2015 in PHP by rajesh
0 votes
35 views



Related Hot Questions

2 Answers

0 votes
ch = curl_init('http://www.google.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie
// multi-cookie variant contributed by @Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);
}
var_dump($cookies);
answered May 28, 2015 by rajesh
0 votes

his does it without regexps, but requires the PECL HTTP extension, may help someone. Cheers

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_HEADER, 1);

$result = curl_exec($ch);


curl_close($ch);


$headers = http_parse_headers($result);

$cookobjs = Array();

foreach($headers AS $k => $v){
    if (strtolower($k)=="set-cookie"){
        foreach($v AS $k2 => $v2){
            $cookobjs[] = http_parse_cookie($v2);
        }
    }
}

$cookies = Array();

foreach($cookobjs AS $row){
    $cookies[] = $row->cookies;
}

$tmp = Array();

///sort k=>v format
foreach($cookies AS $v){
    foreach ($v  AS $k1 => $v1){
        $tmp[$k1]=$v1;
    }
}




$cookies = $tmp;
print_r($cookies);

 

answered May 28, 2015 by rajesh

...