溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

php如何設(shè)置響應(yīng)頭信息

發(fā)布時間:2021-09-24 13:59:01 來源:億速云 閱讀:235 作者:柒染 欄目:編程語言

這篇文章給大家介紹php如何設(shè)置響應(yīng)頭信息,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

php設(shè)置響應(yīng)頭信息的方法是:使用fsockopen()函數(shù)來設(shè)置,例如【<?php $fp = fsockopen("test.com", 80, $errno, $errstr, 30);if (!$fp) {echo "$e...】。

本文操作環(huán)境:windows10系統(tǒng)、php7、thinkpad t480電腦。

在PHP中如果我們需要設(shè)置請求服務(wù)器的響應(yīng)頭信息可以使用fsockopen,curl組件。可能有的小伙伴會瞬間想到header()函數(shù),但是header()函數(shù)只能用來設(shè)置客戶端響應(yīng)的頭信息,它是不能設(shè)置服務(wù)器的頭信息的。我們舉個例子來說明下。

例如:

一、header函數(shù)的用法

    header('WWW-Authenticate: Negotiate');
    header('User-Agent:Mozilla/5.0);

多個直接要寫多個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.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());

會返回自己設(shè)置請求的頭信息

三、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());

會返回自己設(shè)置請求的頭信息

關(guān)于php如何設(shè)置響應(yīng)頭信息就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI