摘要:本文记录了如何在php中获取 curl 请求的请求头信息及相应头信息,以及一些常用请求参数设置,一、curl获取响应头...
一、CURL获取响应头
<?php $curl = curl_init(); $header[] = 'Authorization:Basic '.base64_encode("401_user:401_pwd"); if(isset(getallheaders()['Cookie'])){ $cookie = getallheaders()['Cookie']; $header[] = 'Cookie:'.$cookie; } if(strpos($_SERVER['CONTENT_TYPE'],'form-data')!==false){ $header[] = 'Content-Type: '.getallheaders()['Content-Type']; } $user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"; curl_setopt($curl, CURLOPT_URL, $url); // 设置来源 curl_setopt($curl, CURLOPT_REFERER, $server); // 关闭https验证 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 设置请求头 curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 输出 response 头 curl_setopt($curl, CURLOPT_HEADER, true); // 是否不需要响应的正文,为了节省带宽及时间,在只需要响应头的情况下可以不要正文 // curl_setopt($curl, CURLOPT_NOBODY, true); // 使用上面定义的 ua curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 ); $output = curl_exec($curl); // 获取响应状态码 // $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE ); // 获得响应结果里的:头大小 $response_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); // 获取头信息 $response = substr($output, 0, $response_size); // 获取正文 $data = substr($output, $response_size); // 设置header头 $response_arr = array_filter(explode("\r\n",$response)); foreach ($response_arr as $item){ if(strpos($item,':') !== false){ header($item); } } curl_close($curl);
二、CURL获取请求头
<?php $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //关闭https验证 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); //至关重要,CURLINFO_HEADER_OUT选项可以拿到请求头信息 curl_setopt($curl, CURLINFO_HEADER_OUT, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $bodystr); $output = curl_exec($curl); //通过curl_getinfo()可以得到请求头的信息 $string = curl_getinfo($curl);