php的curl请求如何设置header参数

发布时间:2024-10-15 点击:820
php的curl请求设置header参数的方法:首先使用【curlopt_httpheader】设置http头字段的数组;然后使用一个默认只包含必要的头部字段的http头。
php的curl请求设置header参数的方法:
curl请求参数设置时,curlopt_httpheader设置 http 头字段的数组。
格式: array('content-type: text/plain', 'content-length: 100')
简单示例:
function http_post($surl, $aheader, $adata){ $ch = curl_init(); curl_setopt($ch, curlopt_returntransfer, true); curl_setopt($ch, curlopt_url, $surl); curl_setopt($ch, curlopt_httpheader, $aheader); curl_setopt($ch, curlopt_post, true); curl_setopt($ch, curlopt_postfields, http_build_query($adata)); $sresult = curl_exec($ch); if($serror=curl_error($ch)){ die($serror); } curl_close($ch); return $sresult;} $url = 'https://www.example.com;$header = array('user-agent:mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/63.0.3239.132 safari/537.36');$data = array();$data = http_post($url,$header,$data);当你使用curl向一个url发送http请求的时候,它会使用一个默认只包含必要的头部字段(如:user-agent, host, and accept)的http头。
但在一些个例中,或许你想要在一个http请求中覆盖掉默认的http头或者添加一个新的自定义头部字段。例如,你或许想要重写“host”字段来测试一个负载均衡,或者通过重写"user-agent"字符串来假冒特定浏览器以解决一些访问限制的问题。
最近研究12306火车票相关的数据,想抓取余票信息的时候,本地请求必须设置user-agent"字符串来假冒特定浏览器,不然就请求失败:
/ * 余票查询 * leftticketdto.train_date: 时间 * leftticketdto.from_station: 出发车站电码 * leftticketdto.to_station: 目的车站电码 * purpose_codes: 乘客类型(成人:adult,学生:0x00) * author 洋葱 * @return bool|mixed */function get_left_tickets(){ $url = 'https://kyfw.12306.cn/otn/leftticket/queryz?';// $url = 'https://kyfw.12306.cn/otn/leftticketprice/query?'; $param = [ 'leftticketdto.train_date' => '2019-02-13', 'leftticketdto.from_station' => 'bjp', 'leftticketdto.to_station' => 'shh', 'purpose_codes' => 'adult' ]; $http_param = http_build_query($param); $url = $url.$http_param; //重写"user-agent"字符串来假冒特定浏览器以解决访问限制的问题 $header = array('user-agent:mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/63.0.3239.132 safari/537.36'); $data = curl_request($url,true,'get',null,$header); if($data){ $data = json_decode($data,true); } return $data;}相关视频推荐:php编程从入门到精通

如何让硬盘同时兼容win和mac_硬盘mac和windows通用的方法
自架设服务器与租云平台的
调查发现商业智能和数据分析的应用在疫情期间发挥了重要作用
云服务器租用或购买如何选择辨别
网站以后花中如何更好发挥优化效果?
租用阿里云服务器数据安全吗
如何租用香港阿里云服务器
代理平台没有了-其他问题