很多时候我们都需要保存登录状态才能进行下一步的操作,找了很多资料,都是使用CURL的CURLOPT_COOKIEJAR保存登录信息
没有提到直接临时保存的方法,我这里尝试出来的方法,分享出来
public function saveSessionId($user, $pass){ $pass = md5($pass); $post_data = array ("name" => $user,"password" => $pass); $post = json_encode($post_data); $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); $result = curl_exec($ch); curl_close($ch); $status = json_decode($result, true); $session_id = $status['session_id']; return $session_id; }
然后再需要使用的地方
$session_id = $this->saveSessionId($user, $pass); $cookie = "session_id=$session_id"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIE, $cookie); $data = curl_exec($ch); curl_close($ch); echo $data;
可以卸载公共函数库或者基类里面,方便随时调用