php怎么设置响应头信息
2022-12-02 09:01:16
79
{{single.collect_count}}

php设置响应头信息的方法是:使用fsockopen()函数来设置,例如【<?php $fp = fsockopen("test.com", 80, $errno, $errstr, 30);if (!$fp) {echo "$e...】。

php入门到就业线上直播课:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

本文操作环境:windows10系统、php7、thinkpad t480电脑。

在PHP中如果我们需要设置请求服务器的响应头信息可以使用fsockopen,curl组件。可能有的小伙伴会瞬间想到header()函数,但是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

<?phpfunction 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培训

以上就是php怎么设置响应头信息的详细内容,更多请关注php中文网其它相关文章!

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}