php携带header请求头实现http访问

1,746 阅读1分钟

一、curl方式

/*
 * curl发送post请求
 * url       请求地址
 * postData  要传递的post数据
 * refcode   是否返回请求码
 * refheader 是否返回请求头信息
 * */
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 = addHttpHeader($url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    //在尝试连接时等待的秒数
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
    //设置超时时间,最大执行时间超时时间(单位:s)
    curl_setopt($curl, CURLOPT_TIMEOUT, 300);
    //是否返回请求头信息(http协议头)
    if ($refheader) {
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //追踪句柄的请求字符串(允许查看请求header)
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
    } else {
        curl_setopt($curl, CURLOPT_HEADER, 0);
    }
	//解释gzip加密压缩
	curl_setopt($curl, CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip, deflate'));
    curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
	//尝试连接
    if (curl_exec($curl) === false) {
		return "连接失败,Error:".curl_error($curl);
    } 	
	//执行命令
	$result = curl_exec($curl);
	//去空格
	$result = trim($result);
	//转换字符编码
	$result = mb_convert_encoding($result, 'utf-8', 'UTF-8,GBK,GB2312,BIG5');
	//解决返回的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
 */
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;
}

二、file_get_contents方式

/**
 * file_get_contents发送post请求
 * @param url       请求地址
 * @param postData  要传递的post数据
 * @param refcode   是否返回请求码
 * @param refheader 是否返回请求头信息
 */
function file_post($url, $post_data,$refcode = false, $refheader = false) {
    $postdata = http_build_query($post_data);
    $options = array('http' => array('method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $postdata, 'timeout' => 300
    // 超时时间(单位:s)
    ));
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
	//去空格
	$result = trim($result);
	//转换字符编码
	$result = mb_convert_encoding($result, 'utf-8', 'UTF-8,GBK,GB2312,BIG5');
	//解决返回的json字符串中返回了BOM头的不可见字符(某些编辑器默认会加上BOM头)
	$result = trim($result,chr(239).chr(187).chr(191));
    //是否返回状态码
    if ($refcode) {
		$httpcode=$http_response_header[0];
		//是否返回请求头信息(http协议头)
		if ($refheader) {
			$header='';
			foreach ($http_response_header as $key => $value) {
				$header.=$value."\r\n";
			}
			$header.="\r\n";
			$result=$header.$result;
		}
        $html = array("httpcode" => $httpcode, "result" => $result);
        return $html;
    } else {
        return $result;
    }
}