Im using curl through php to fetch a url. I am successfully able to download the page, headers and all. However, the cookies returned by any page do not get saved to the specified file. I've checked permissions etc, and nothing seems out of the ordinary. I am beginning to think something is off in my code.
$get_cookie_page = 'http://www.google.ca';
echo curl_download($get_cookie_page);
function curl_download($Url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
$http_headers = array(
'Host: www.google.ca',
'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2',
'Accept: */*',
'Accept-Language: en-us,en;q=0.5',
'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Connection: keep-alive'
);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $http_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
Any help appreciated.
You can't. The only way this would work is if you use persistent cookies in your curl request. CURL can keep cookies itself. Assign a session ID to the cookie file (in curl) so subsequent requests get the same cookies.
This is the PHP syntax for cookie creation: setcookie($name, $value, $expires, $path, $domain, $secure, $httponly); The first variable is your cookie name, which you can use to read the value like this: $_COOKIE['YOUR COOKIE NAME'];
php file with the following contents. $url = 'https://www.example.com' ; $curl = curl_init(); curl_setopt( $curl , CURLOPT_URL, $url );
Thanks everyone for all the help. However, the problem was something else entirely. I probably should have mentioned that I am working on a Windows server and cURL was unable to read the path to cookie.txt
.
Using:
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . '/cookie.txt');
instead of:
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
solved the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With