php CURL模拟登陆+获取cookie


/*
 * 模拟post请求
 */
function post_curl($url, $params=[], $headers=[]){
   $httpInfo = array();
   $ch = curl_init();
   
   curl_setopt($ch, CURLOPT_HEADER, 1);
   curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
   curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36' );
   curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
   curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
   curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
   
   curl_setopt( $ch , CURLOPT_POST , true );
   curl_setopt( $ch , CURLOPT_POSTFIELDS , http_build_query($params));
   curl_setopt( $ch , CURLOPT_URL , $url );
   
  
   $response = curl_exec( $ch );
   if ($response === FALSE) {
      return false;
   }
    
    curl_close( $ch );
    return $response;
}

$re = post_curl($http, $data, 1);
// 解析HTTP数据流
list($header, $body) = explode("\r\n\r\n", $re);
// 解析COOKIE
preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
//请求的时候headers 带上cookie就可以了
$cookie = explode(';', $matches[1])[0];

 

你可能感兴趣的:(PHP)