PHP设置头信息及取得返回头信息的方法


本文实例讲述了PHP设置头信息及取得返回头信息的方法。分享给大家供大家参考,具体如下:

设置请求的头信息,我们可以用header函数,可以用fsockopen,可以用curl等,本文主要讲的是用curl来设置头信息,并取得返回后的头信息。

一、请求方设置自己的头信息,header.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://localhost/test/header2.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);
?>

二、被请求方,取得头信息,header2.php

<?php
print_r($_SERVER); //头信息里面有内容绝大部分是放在系统变量里面的
?>

三、看一下header.php请求的结果

string(1045) "Array
(
[HTTP_HOST] => localhost
[CONTENT_TYPE] => text/xml; charset=utf-8
[HTTP_ACCEPT] => */*
[HTTP_REFERER] => http://localhost/
[HTTP_USER_AGENT] => Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1)
[HTTP_X_FORWARDED_FOR] => 10.1.11.1
[CONTENT_LENGTH] => 380
[PATH] => /usr/local/bin:/usr/bin:/bin
[SERVER_SIGNATURE] => <address>Apache/2.2.16 (Ubuntu) Server at localhost Port 80</address>
。。。。。。。。。。。。。。。。。。。。。。。。。。。。
)

上面那几个,我们可以明显看到,是我设置的头信息。

四、取得返回的头信息

PHP基本语法入门教程》、《php面向对象程序设计入门教程》及《php curl用法总结》

希望本文所述对大家PHP程序设计有所帮助。


« 
» 

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3