简体   繁体   English

如何使用php从对cURL请求的响应中保存cookie?

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

Im using curl through php to fetch a url. 我通过PHP使用curl来获取网址。 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. 但是,任何页面返回的cookie都不会保存到指定的文件中。 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 . 我可能应该提到我在Windows服务器上工作,而cURL无法读取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. 使用cookie jar文件的绝对路径,以便确定保存的位置,从而确保您拥有在该处写入的正确权限。

curl stores all cookies it knows of to the file, including so called session cookies (that are without an expiry time) curl将它知道的所有cookie存储到文件中,包括所谓的会话cookie(没有到期时间)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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