file_get_contents接收cookie [英] file_get_contents receive cookies

查看:443
本文介绍了file_get_contents接收cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当执行 file_get_contents 请求时,是否可以接收远程服务器设置的Cookie?

Is it possible to receive the cookies set by the remote server when doing a file_get_contents request?

我需要php执行http请求,存储cookie,然后使用存储的Cookie发出第二个http请求。

I need php to do a http request, store the cookies, and then make a second http request using the stored cookies.

推荐答案

您应该使用 cURL cURL 实现一个名为cookie jar的功能,允许保存cookie并将其重用于后续请求。

you should use cURL for that purpose, cURL implement a feature called the cookie jar which permit to save cookies in a file and reuse them for subsequent request(s).

这里有一个快速代码snipet如何做:

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

注意:必须注意您应该有pecl扩展名在PHP中编译)安装或您将无法访问cURL API。

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.

这篇关于file_get_contents接收cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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