[PHP] CURL获取cookie,模拟登录获取数据

  • Post author:
  • Post category:php



需求:通过CURL先登录,然后获取登录后的cookie,在请求数据接口的时候带上这个cookie即可!


直接贴代码:

 1 <?php
 2 
 3 class CurlLoginDemo
 4 {
 5     public $config = [
 6         //登录接口和参数
 7         'login_url' => 'http://localhost/login',
 8         'login_post_data' => [
 9             'username' => 'aaa',
10             'password' => 'aaa',
11         ],
12         
13         //数据接口
14         'list_url' => 'http://localhost/list',
15         'list_post_data' => [
16             'page' => 1,
17             'rows' => 30,
18         ],
19      ];
20     public $cookie = '';
21 
22     //登录接口,获取cookie
23     public function login()
24     {
25         $re = $this->post_curl($this->config['login_url'], $this->config['login_post_data'], 1);
26         
27         // 解析HTTP数据流
28         list($header, $body) = explode("\r\n\r\n", $re);
29         // 解析COOKIE
30         preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
31         //请求的时候headers 带上cookie就可以了
32         $cookie = explode(';', $matches[1])[0];
33 
34         $this->cookie = trim($cookie);
35     }
36 
37     //执行登录后的操作
38     public function execute()
39     {
40         $re = $this->post_curl($this->config['list_url'], $this->config['list_post_data']);
41 
42         //$json = json_decode($re, true);
43 
44         var_dump($re);
45     }
46 
47     //发送请求
48     function post_curl($url, $params=[], $isShowHeader=0){
49         $httpInfo = array();
50         $ch = curl_init();
51 
52         curl_setopt( $ch, CURLOPT_HEADER, $isShowHeader);
53         curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
54         curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36' );
55         curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
56         curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
57         curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
58 
59         curl_setopt( $ch , CURLOPT_POST , true );
60         curl_setopt( $ch , CURLOPT_POSTFIELDS , http_build_query($params));
61         curl_setopt( $ch , CURLOPT_URL , $url );
62 
63         if($this->cookie){
64             curl_setopt($ch, CURLOPT_COOKIE, $this->cookie);//设置cookie
65         }
66 
67         $response = curl_exec( $ch );
68         if ($response === FALSE) {
69           return false;
70         }
71 
72         curl_close( $ch );
73         return $response;
74     }
75 
76     //启动
77     public function start()
78     {
79         try{
80             $this->login();
81             if(!$this->cookie){
82                 throw new \Exception("登录失败!");
83             }
84             $this->execute();
85         }catch(\Exception $e){
86             print($e);
87         }
88     }
89 
90 }
91 
92 $obj = new CurlLoginDemo();
93 $obj->start();

转载于:https://www.cnblogs.com/reader/p/11593974.html