PHP Curl 保持会话连接

Posted: 2019-01-15  By  vilay  |  Views(156)

PHP 请求接口的时候保持cookie 会话连接的方法

function curlRequest($url,$data,$headers=[])
{
        $cookie_file = '/tmp/cookie.txt';
        $data = json_encode($data);
        $ch = curl_init();
        $user_token = getAuthToken();
        $headers = [
                'Content-Type:application/json;charset=utf-8',
                'Content-Length:'.strlen($data),
        ];
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
        curl_setopt ( $ch, CURLOPT_COOKIEJAR, $cookie_file);
        curl_setopt ( $ch, CURLOPT_COOKIEFILE, $cookie_file); 
        $result = curl_exec($ch);

        if ($result == false) {
                $error = curl_error($ch);
                return false;
        }
        curl_close($ch);

        $result = json_decode($result, true);
        return $result;
}