The method for php to set response header information is to use the fsockopen() function to set it, for example [
The operating environment of this article: windows10 system, php7, thinkpad t480 computer.
In PHP, if we need to set the response header information of the request server, we can use fsockopen and curl components. Some friends may instantly think of the header() function, but the header() function can only be used to set The client's response header information cannot set the server's header information. Let's give an example to illustrate.
For example:
1. Usage of header function
header('WWW-Authenticate: Negotiate'); header('User-Agent:Mozilla/5.0);
Multiple headers need to be written directly and cannot be connected together
2. Usage of fsockopen function
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());
will return the header information of the request you set
3. Use of curl component
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());
will return the header information of your own request
Recommended learning: php training
The above is the detailed content of How to set response header information in php. For more information, please follow other related articles on the PHP Chinese website!