PHP uses curl to send post requests and return request header information

You can return request header information and request status code. The effect diagram is as follows:

 

Method function: 

	/* 
     * curl发送post请求,并返回请求头信息
     * url:       访问路径  
     * postData:  要传递的post数据
	 * refcode:   是否返回请求码	
	 * refheader: 是否返回请求头信息
     * */ 
	protected function curl_post($url,$postData,$refcode=false,$refheader=false) { 		
		$curl = curl_init();
		//设置提交的url
		curl_setopt($curl, CURLOPT_URL, $url);
		//设置获取的信息以文件流的形式返回,而不是直接输出 
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//忽略证书(关闭https验证)
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		//设置post方式提交  
		curl_setopt($curl, CURLOPT_POST, 1);
		//设置post数据
		$postFields = http_build_query($postData);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);	
		//添加请求头信息		
		//$headers = $this->addHttpHeader($url);
		//curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		//设置超时时间,最大执行时间超时时间(单位:s)
		curl_setopt($curl, CURLOPT_TIMEOUT, 120);
		//是否返回请求头信息(http协议头)
		if($refheader){
			curl_setopt($curl, CURLOPT_HEADER, 1);
			//追踪句柄的请求字符串(允许查看请求header)		
			curl_setopt($curl, CURLINFO_HEADER_OUT, true); 
		}else{
			curl_setopt($curl, CURLOPT_HEADER, 0);
		}
		//执行命令
		$result = curl_exec($curl);
		//解决返回的json字符串中返回了BOM头的不可见字符(某些编辑器默认会加上BOM头)
	    $result = trim($result,chr(239).chr(187).chr(191));
		//获取状态码
		$httpcode = curl_getinfo ($curl, CURLINFO_HTTP_CODE);
		//关闭URL请求
		curl_close($curl);
		//是否返回请求码
		if($refcode){
			$html=array(
				"httpcode" => $httpcode,
				"result" => $result
			);
			return $html;
		}else{
			return $result;
		}
    }
	/**
	 * 添加请求头
	 * @param $url 请求网址
	 * @return array
	 */
	protected function addHttpHeader($url)
	{
		 // 解析url
		 $temp = parse_url($url);
		 $query = isset($temp['query']) ? $temp['query'] : ''; 
		 $path = isset($temp['path']) ? $temp['path'] : '/'; 
		 $header = array (
			 "POST {$path}?{$query} HTTP/1.1",
			 "Host: {$temp['host']}",
			 "Referer: http://{$temp['host']}/",
			 "Content-Type: application/x-www-form-urlencoded",
			 'Accept: application/json, text/javascript, */*; q=0.01',
			 'Accept-Encoding:gzip, deflate, br',
			 'Accept-Language:zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
			 'Connection:keep-alive',
			 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0',
			 'X-Requested-With: XMLHttpRequest',
		 );
		return $header;
	} 

 

Guess you like

Origin blog.csdn.net/qq15577969/article/details/112735126