小編給大家分享一下php中設置請求頭信息的方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
php設置請求頭信息的方法:1、使用header函數設置請求頭信息;2、通過fsockopen函數設置請求頭信息;3、通過使用curl組件設置請求頭信息。
本文操作環境:Windows7系統、PHP7.1版,DELL G3電腦
php怎么設置請求頭信息?
php設置http請求頭信息和響應頭信息
設置請求服務器的頭信息可以用fsockopen,curl組件,header函數只能用來設置客戶端響應的頭信息,不能設置服務器的頭信息.
一.header函數的用法
header('WWW-Authenticate: Negotiate');
header('User-Agent:Mozilla/5.0);多個直接要寫多個header,不可以連接在一起
二.fsockopen函數的用法
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.1\r\n";
$out .= "Host: test.com\r\n";
$out .= "name:longqiqi\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>2.php
print_r(getallheaders());//會返回自己設置請求的頭信息
三.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); //設置頭信息的地方
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());//會返回自己設置請求的頭信息
以上是“php中設置請求頭信息的方法”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。