简体   繁体   中英

How do I save cookies from a response to a cURL request using php?

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.

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.

Use an absolute path to the cookie jar file so that you're sure where it is saved and thus you know you have the right permission to write there.

curl stores all cookies it knows of to the file, including so called session cookies (that are without an expiry time)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM