问题
I am connecting to an API service which authenticates users using cookies. I make these two statements from command prompt 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 am using
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
in login.php
and
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
in get_data.php
It is not working. Cookie file is getting created but second curl is not reading it.
Is this the right way to do it ? Do I have to read the cookie file seperately and set the header Cookie ? Any help would appreciated. Thanks.
回答1:
This will do the trick. I run it against 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);
?>
See other examples for how to effectively parse such as string.
回答2:
is there any method to see the curl request headers. Can I get it from curl instance ? or is there any tool like fiddler for Mac (I am working Mac OS ) ?
Yes, you can get the request headers with the following:
<?php
...
curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking
$result = curl_exec($ch);
var_dump(curl_getinfo($ch, CURLINFO_HEADER_OUT)); // request headers
?>
回答3:
In PHP 5.5.0 it looks like you can now get the cookies in one line but I only get back an empty array using this with PHP 7.1.0:
CURLINFO_COOKIELIST - get all known cookies
$cookies = curl_getinfo($curl, CURLINFO_COOKIELIST);
来源:https://stackoverflow.com/questions/9714360/reading-cookie-when-using-curl-in-php-how-to