如何使用php保存对cURL请求的响应中的cookie? [英] How do I save cookies from a response to a cURL request using php?

查看:376
本文介绍了如何使用php保存对cURL请求的响应中的cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过php使用curl来获取URL.我可以成功下载页面,标题和所有内容.但是,任何页面返回的cookie都不会保存到指定文件中.我已经检查了权限等,似乎没有什么不寻常的.我开始认为我的代码中有问题.

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;
}

任何帮助表示赞赏.

推荐答案

感谢所有人的所有帮助.但是,问题完全是另外一个问题.我可能应该提到我正在Windows服务器上工作,而cURL无法读取cookie.txt的路径.

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.

使用:

curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . '/cookie.txt');

代替:

curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

解决了问题.

这篇关于如何使用php保存对cURL请求的响应中的cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆