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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7917970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:38:27  来源:igfitidea点击:

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

phpcurl

提问by ???

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.

我通过 php 使用 curl 来获取一个 url。我能够成功下载页面、标题和所有内容。但是,任何页面返回的 cookie 都不会保存到指定的文件中。我检查了权限等,似乎没有什么异常。我开始觉得我的代码有些不对劲。

$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.

任何帮助表示赞赏。

回答by ???

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.

解决了这个问题。

回答by Daniel Stenberg

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(没有过期时间)