首页  >  文章  >  后端开发  >  php怎么设置请求头信息

php怎么设置请求头信息

藏色散人
藏色散人原创
2021-06-17 09:24:385468浏览

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