php 带cookie请求数据
网站后台向其它网页请求数据时,因为有的网页必须要登录,所以必须得带上cookie。
以下代码都已经封装好,直接直接传入cookie和post数据。
通用型方法
function HttpAction($url,$post = array(),$cookie = array()){ if (is_array($cookie)){ $cookies = ''; foreach ($cookie as $key => $value) { $cookies .= $key.'='.$value.';'; } }else{ $cookies = $cookie; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_COOKIE, $cookies); $result = curl_exec($ch); curl_close($ch); return $result;}
zblog方法
function HttpAction($url,$post = array(),$cookie = array()){ if (is_array($cookie)){ $cookies = ''; foreach ($cookie as $key => $value) { $cookies .= $key.'='.$value.';'; } }else{ $cookies = $cookie; } $ask = Network::Create(); $ask->open('POST', $url); $ask->enableGzip(); $ask->setTimeOuts(120, 120, 0, 0); $ask->setRequestHeader('Cookie', $cookies); $ask->send($post); if ($ask->status == 200){ return $ask->responseText; } return false;}
Network类是zblog系统已经封装好的方法,建议使用这个。
cookie说明
输入的cookie,可以是数组,也可以是字符串。
数组
array( 'token' => '1111111111111', 'id' => '50',);
字符串
token=1111111111111;id=50