• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 4年前 (2022-01-25) 28次浏览 已收录 0个评论

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

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

一、请求方设置自己的头信息,header.php


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


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

string(10<div>本文来*源gaodai^.ma#com搞#代!码网</div><pre>搞gaodaima代码

45) “Array([HTTP_HOST] => localhost[CONTENT_TYPE] => text/xml; charset=utf-8[HTTP_ACCEPT] => */*[HTTP_REFERER] => http://localhost/%5BHTTP_USER_AGENT%5D => 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] => Apache/2.2.16 (Ubuntu) Server at localhost Port 80

。。。。。。。。。。。。。。。。。。。。。。。。。。。。)

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

四、取得返回的头信息

curl_setopt($ch, CURLOPT_HEADER, 1); //取得返回头信息

我们把CURLOPT_HEADER设置成1,在取得的结果当中,显示数组的前面会有这些信息

string(1239) "HTTP/1.1 200 OKDate: Fri, 27 May 2011 01:57:57 GMTServer: Apache/2.2.16 (Ubuntu)X-Powered-By: PHP/5.3.3-1ubuntu9.5Vary: Accept-EncodingContent-Length: 1045Content-Type: text/htmlArray( [HTTP_HOST] => localhost [CONTENT_TYPE] => text/xml; charset=utf-8 [HTTP_ACCEPT] => */*

五、$_SERVER部分头信息是拿不到的

修改一下header.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: " . strlen($xml) ."\r\n\r\n" .$xml, //修改1 "Connection: Close" ); return $header;}$xml = ' //修改2  adsfadsf asdfasdf asdf asdf asdfasd <title>asdfasdf</title> asdfadsf asdfasdf asdfasdf ';$interface = 'http://localhost/test/header2.php';$header = FormatHeader($interface,'10.1.11.1',$xml); //修改3$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里面,打印$_SERVER不可能把头信息中的xml打印出来。这个时候,我们在header2.php后面加上以下二行

$raw_post_data = file_get_contents('php://input', 'r');var_dump($raw_post_data);

这样就可以取到$xml的内容,并且只会取$xml的内容。

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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP设置头信息及取得返回头信息的方法_PHP

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址