Reading cookie when using curl in php, how?

I am connecting to an API service that authenticates users using cookies. I do these two statements from the command line and it works.

curl -d "u=username&p=password" -c ~/cookiejar https://domain/login

curl -b https://domain/getData

Now I want to make two equivalent php files login.php and get_data.php using curl.

I use

curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);

in login.php

and

curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

in get_data.php

He does not work. A cookie is created, but the second curl does not read it. Is it correct? Should I read the cookie separately and set the header Cookie? Any help would be appreciated. Thank.

+5
source share
3 answers

This will do the trick. I use it for Google.com as an example:

<?PHP

// open a site with cookies
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com");
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0');
curl_setopt($ch, CURLOPT_HEADER  ,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER  ,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION  ,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$content = curl_exec($ch);

// get cookies
$cookies = array();
preg_match_all('/Set-Cookie:(?<cookie>\s{0,}.*)$/im', $content, $cookies);

print_r($cookies['cookie']); // show harvested cookies

// basic parsing of cookie strings (just an example)
$cookieParts = array();
preg_match_all('/Set-Cookie:\s{0,}(?P<name>[^=]*)=(?P<value>[^;]*).*?expires=(?P<expires>[^;]*).*?path=(?P<path>[^;]*).*?domain=(?P<domain>[^\s;]*).*?$/im', $content, $cookieParts);
print_r($cookieParts);

?>

. , , .

+14

- . curl? - , Mac ( Mac OS)?

, :

<?php
  ...
  curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking
  $result = curl_exec($ch);
  var_dump(curl_getinfo($ch, CURLINFO_HEADER_OUT)); // request headers
?>
+1

In PHP 5.5.0, it looks like you can now receive cookies on a single line, but I am returning an empty array using this with PHP 7.1.0:

CURLINFO_COOKIELIST - get all known cookies

$cookies = curl_getinfo($curl, CURLINFO_COOKIELIST);
0
source

All Articles