php file_get_contents 接收 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1797510/
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
file_get_contents receive cookies
提问by Louis W
Is it possible to receive the cookies set by the remote server when doing a file_get_contentsrequest?
做file_get_contents请求时是否可以接收远程服务器设置的cookies ?
I need php to do a http request, store the cookies, and then make a second http request using the stored cookies.
我需要 php 来执行 http 请求,存储 cookie,然后使用存储的 cookie 发出第二个 http 请求。
回答by Ja?ck
There's a magic variable for this, called $http_response_header; it's an array comprising all headers that were received. To extract the cookies you have to filter out the headers that start with Set-Cookie:.
为此有一个神奇的变量,称为$http_response_header; 它是一个包含收到的所有标头的数组。要提取 cookie,您必须过滤掉以Set-Cookie:.
file_get_contents('http://example.org');
$cookies = array();
foreach ($http_response_header as $hdr) {
if (preg_match('/^Set-Cookie:\s*([^;]+)/', $hdr, $matches)) {
parse_str($matches[1], $tmp);
$cookies += $tmp;
}
}
print_r($cookies);
An equivalent but less magical approach would be to use stream_get_meta_data():
一种等效但不那么神奇的方法是使用stream_get_meta_data():
if (false !== ($f = fopen('http://www.example.org', 'r'))) {
$meta = stream_get_meta_data($f);
$headers = $meta['wrapper_data'];
$contents = stream_get_contents($f);
fclose($f);
}
// $headers now contains the same array as $http_response_header
回答by RageZ
you should use cURLfor that purpose, cURLimplement a feature called the cookie jar which permit to save cookies in a file and reuse them for subsequent request(s).
您应该cURL为此目的使用,cURL实现一个称为 cookie jar 的功能,它允许将 cookie 保存在文件中并在后续请求中重用它们。
Here come a quick code snipet how to do it:
这里有一个快速的代码片段如何做到这一点:
/* STEP 1. let's create a cookie file */
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
/* STEP 2. visit the homepage to set the cookie properly */
$ch = curl_init ("http://somedomain.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
/* STEP 3. visit cookiepage.php */
$ch = curl_init ("http://somedomain.com/cookiepage.php");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
note: has to be noted you should have the pecl extension (or compiled in PHP) installed or you won't have access to the cURL API.
注意:必须注意,您应该安装 pecl 扩展(或在 PHP 中编译),否则您将无法访问 cURL API。
回答by Laereom
I realize this is, late, but there is actually a way to at least receive individual cookies sent by the server.
我意识到这已经很晚了,但实际上有一种方法至少可以接收服务器发送的单个 cookie。
I'm assuming you know how to do the whole stream_create_context business to get your file_get_contents http request rolling, and you just need assistance actually setting the cookies.
我假设您知道如何完成整个 stream_create_context 业务来让您的 file_get_contents http 请求滚动,并且您只需要实际设置 cookie 的帮助。
After running file_get_contents on a url, the (unfortunately, non-associative) array $http_response_header is set.
在 url 上运行 file_get_contents 后,(不幸的是,非关联)数组 $http_response_header 被设置。
If the server is sending back a cookie, one of them will start with 'Set-Cookie: ', which you can extract with substr.
如果服务器发回一个 cookie,其中一个将以“Set-Cookie:”开头,您可以使用 substr 提取它。
However, at the moment, it appears to me that one can only access -one- Set-Cookie through this variable, which is a limitation I am currently trying to find a way to work around.
但是,目前,在我看来只能通过此变量访问 -one-Set-Cookie,这是我目前正在尝试寻找解决方法的限制。
回答by Darren Cook
Following on from Laereom's answer, here is how to get multiple cookies:
继 Laereom 的回答之后,以下是获取多个 cookie 的方法:
$cookies=array();
foreach($http_response_header as $s){
if(preg_match('|^Set-Cookie:\s*([^=]+)=([^;]+);(.+)$|',$s,$parts))
$cookies[$parts[1]]=$parts[2];
}
NOTES:
笔记:
- I'm liberal with the regex; study the RFCs if you want to be more precise (i.e. to reject badly formed cookie data)
- You'll find path=, expires=, etc. in $parts[3]. I'd suggest
explode(';',$parts[3])then another loop to process it (because I'm not sure if there is a fixed order for these attributes. - If two cookies have the same name part, only the last survives, which appears to be correct. (I happen to have this situation in my current project; I assume it is a bug in the website I'm screen-scraping.)
- 我对正则表达式很自由;如果您想更精确(即拒绝格式错误的 cookie 数据),请研究 RFC
- 您将在 $parts[3] 中找到 path=、expires= 等。我建议
explode(';',$parts[3])再使用另一个循环来处理它(因为我不确定这些属性是否有固定的顺序。 - 如果两个 cookie 具有相同的名称部分,则只有最后一个存活,这似乎是正确的。(我在当前项目中碰巧遇到这种情况;我认为这是我正在抓取屏幕的网站中的错误。)
回答by soulmerge
You can either install and use the PECL extension for HTTP, or make sure your php installation was compiled with the optional curl library.
回答by Tim Lytle
I believe you co do it pretty easily with the Zend_Http object. Here is the documentation about adding cookiesto a request.
我相信你可以很容易地使用 Zend_Http 对象来完成。这是有关向请求添加 cookie的文档。
To get the cookies from a request (automatically retrieved I believe), just use getCookieJar()on the Zend_Http object.
要从请求中获取 cookie(我相信是自动检索的),只需getCookieJar()在 Zend_Http 对象上使用。
That should be easy to implement; however, the php manual has a user comment on how to deal with cookies using the http stream.
这应该很容易实现;然而,php 手册有一个关于如何使用 http 流处理 cookie的用户评论。

