php設(shè)置請(qǐng)求頭信息的方法:1、使用header函數(shù)設(shè)置請(qǐng)求頭信息;2、通過(guò)fsockopen函數(shù)設(shè)置請(qǐng)求頭信息;3、通過(guò)使用curl組件設(shè)置請(qǐng)求頭信息。
本文操作環(huán)境:Windows7系統(tǒng)、PHP7.1版,DELL G3電腦
php怎么設(shè)置請(qǐng)求頭信息?
php設(shè)置http請(qǐng)求頭信息和響應(yīng)頭信息
設(shè)置請(qǐng)求服務(wù)器的頭信息可以用fsockopen,curl組件,header函數(shù)只能用來(lái)設(shè)置客戶端響應(yīng)的頭信息,不能設(shè)置服務(wù)器的頭信息.
一.header函數(shù)的用法
header('WWW-Authenticate: Negotiate'); header('User-Agent:Mozilla/5.0);
多個(gè)直接要寫多個(gè)header,不可以連接在一起
二.fsockopen函數(shù)的用法
1.php
<?php $fp = fsockopen("test.com", 80, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)<br />n"; } else { $out = "GET /2.php HTTP/1.1rn"; $out .= "Host: test.comrn"; $out .= "name:longqiqirn"; $out .= "Connection: Closernrn"; fwrite($fp, $out); while (!feof($fp)) { echo fgets($fp, 128); } fclose($fp); } ?>
2.php
print_r(getallheaders());//會(huì)返回自己設(shè)置請(qǐng)求的頭信息
三.curl組件的使用
1.php
<?php function FormatHeader($url, $myIp = null,$xml = null) { // 解析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']}", "Content-Type: text/xml; charset=utf-8", 'Accept: */*', "Referer: http://{$temp['host']}/", 'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1)', "X-Forwarded-For: {$myIp}", "Content-length: 380", "Connection: Close" ); return $header; } $interface = 'http://test.com/2.php'; $header = FormatHeader($interface,'10.1.11.1'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $interface); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //設(shè)置頭信息的地方 curl_setopt($ch, CURLOPT_HEADER, 0); //不取得返回頭信息 curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); var_dump($result); ?>
2.php
print_r(getallheaders());//會(huì)返回自己設(shè)置請(qǐng)求的頭信息
推薦學(xué)習(xí):《PHP視頻教程》