在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怎么设置响应头信息的详细内容。
