首頁  >  文章  >  後端開發  >  php怎麼設定請求頭訊息

php怎麼設定請求頭訊息

藏色散人
藏色散人原創
2021-06-17 09:24:385469瀏覽

php設定請求頭資訊的方法:1、使用header函數設定請求頭資訊;2、透過fsockopen函數設定請求頭資訊;3、透過使用curl元件設定請求頭資訊。

php怎麼設定請求頭訊息

本文操作環境: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[&#39;query&#39;]) ? $temp[&#39;query&#39;] : &#39;&#39;;
 
 $path = isset($temp[&#39;path&#39;]) ? $temp[&#39;path&#39;] : &#39;/&#39;;
 
 $header = array (
 
 "POST {$path}?{$query} HTTP/1.1",
 
 "Host: {$temp[&#39;host&#39;]}",
 
 "Content-Type: text/xml; charset=utf-8",
 
 &#39;Accept: */*&#39;,
 
 "Referer: http://{$temp[&#39;host&#39;]}/",
 
 &#39;User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1)&#39;,
 
 "X-Forwarded-For: {$myIp}",
 
 "Content-length: 380",
 
 "Connection: Close"
 
 );
 return $header;
} 
 
$interface = &#39;http://test.com/2.php&#39;;
 
$header = FormatHeader($interface,&#39;10.1.11.1&#39;);
 
$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影片教學

以上是php怎麼設定請求頭訊息的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn