温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php中设置请求头信息的方法

发布时间:2021-06-17 10:24:31 来源:亿速云 阅读:1395 作者:小新 栏目:编程语言

小编给大家分享一下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中设置请求头信息的方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI