用户评论:

Backslider (2012-02-15 19:06:56)

It should be noted that rather than returning "false" on failure, this function (and others) return a big phat WARNING that will halt your script in its tracks if you do not have error reporting /warning turned off.

Thats just insane! Any function that does something like fetch a URL should simply return false, without a warning, if the URL fails for whatever reason other than it is badly formatted.

damolp at hotmail dot com (2011-07-03 17:43:51)

I found that this function is the slowest in obtaining the headers of a page probably because it uses a GET request rather then a HEAD request. Over 10,000,000 trials of obtaining the headers of a page from a server i found the following (results in seconds).

cURL: Mean: 0.584127946. Sigma: 0.050581736.

fsocketopen: Mean: 0.622114251. Sigma: 0.263170424.

get_headers: Mean: 0.90375551. Sigma: 0.273823419.

cURL was the fastest with fsocketopens being the second fastest. I noticed as well that fsocketopen had some outliers where as cURL did not.

Lukas Najduk (2011-01-11 03:36:50)

Unfortunately there is still no useful output format to handle redirects.

This function will bring all non-broken headers into a usable format. Too bad it has to call the get_headers() funtion 2 times, but i dont see any other possibility right now.

if (empty($headers)) {

return array();

}$splitmarks= array();

foreach ($headersas$key=>$h) {

if (is_numeric($key)) {array_push($splitmarks,$h);

}

}// get the "real" headers$headers_final= array();$i=0;$headers=get_headers($crawl_uri);

foreach ($headersas$head) {// if the value is one of the splitmarks, start the next headerif (array_key_exists($i,$splitmarks) &&$head===$splitmarks[$i]) {$i++;

}

else {// get the headers name$tmp=explode(": ",$head,2);// check if the header is already existing, if yes, parse the similar header to an arrayif (!empty($headers_final[$i-1][$tmp[0]])) {

if (is_array($headers_final[$i-1][$tmp[0]])) {array_push($headers_final[$i-1][$tmp[0]],$tmp[1]);

}

else {$headers_final[$i-1][$tmp[0]] = array($headers_final[$i-1][$tmp[0]],$tmp[1]);

}

}

else {$headers_final[$i-1][$tmp[0]] =$tmp[1];

}

}

}

return$headers_final;

}?>

Weboide (2010-09-25 18:13:47)

Note that get_headers **WILL follow redirections** (HTTP redirections). New headers will be appended to the array if $format=0. If $format=1 each redundant header will be an array of multiple values, one for each redirection.

For example:

$url='http://google.com';var_dump(get_headers($url,0));/*array(18) {

[0]=>  string(30) "HTTP/1.0 301 Moved Permanently"

[1]=>  string(32) "Location: http://www.google.com/"

[2]=>  string(38) "Content-Type: text/html; charset=UTF-8"

[3]=>  string(35) "Date: Sun, 26 Sep 2010 00:59:50 GMT"

[4]=>  string(38) "Expires: Tue, 26 Oct 2010 00:59:50 GMT"

[5]=>  string(38) "Cache-Control: public, max-age=2592000"

....

string(15) "HTTP/1.0 200 OK"

[10]=>  string(35) "Date: Sun, 26 Sep 2010 00:59:51 GMT"

[11]=>  string(11) "Expires: -1"

[12]=>  string(33) "Cache-Control: private, max-age=0"

.....

}*/

/*===========================*/var_dump(get_headers($url,1));/*array(11) {

[0]=>

string(30) "HTTP/1.0 301 Moved Permanently"

["Location"]=>  string(22) "http://www.google.com/"

["Content-Type"]=>  array(2) {

[0]=>    string(24) "text/html; charset=UTF-8"

[1]=>    string(29) "text/html; charset=ISO-8859-1"

}

["Date"]=>  array(2) {

[0]=>    string(29) "Sun, 26 Sep 2010 01:03:39 GMT"

[1]=>    string(29) "Sun, 26 Sep 2010 01:03:39 GMT"

}

["Expires"]=>  array(2) {

[0]=>    string(29) "Tue, 26 Oct 2010 01:03:39 GMT"

[1]=>    string(2) "-1"

}

["Cache-Control"]=>  array(2) {

[0]=>    string(23) "public, max-age=2592000"

[1]=>    string(18) "private, max-age=0"

}

.....

}*/?>

nick at innovaweb dot co dot uk (2010-05-02 17:28:29)

Seems like there are some people who are looking for only the 3-digit HTTP response code  - here is a quick and nasty solution:

returnsubstr($headers[0],9,3);

}?>

How easy is that? Echo the function containing the URL you want to check the response code for, and voilà. Custom redirects, alternative for blocked is_file() or flie_exists() functions (like I seem to have on my servers) hence the cheap workaround. But hey - it works!

Pudding

php at hm2k dot org (2010-01-28 10:20:25)

* Fetches all the real headers sent by the server in response to a HTTP request without redirects

*

* @link      http://php.net/function.get_headers

* @link      http://bugs.php.net/bug.php?id=50719

*/functionget_real_headers($url,$format=0,$follow_redirect=0) {

if (!$follow_redirect) {//set new default options$opts= array('http'=>

array('max_redirects'=>1,'ignore_errors'=>1)

);stream_context_get_default($opts);

}//get headers$headers=get_headers($url,$format);//restore default optionsif (isset($opts)) {$opts= array('http'=>

array('max_redirects'=>20,'ignore_errors'=>0)

);stream_context_get_default($opts);

}//returnreturn$headers;

}?>

gabe at vtunnel dot com (2009-04-22 01:23:51)

In some cases, you don't want get_headers to follow redirects. For example, some of my servers can access a particular website, which sends a redirect header. The site it is redirected to, however, has me firewalled. I need to take the 302 redirected url, and do something to it to give me a new url that I *can* connect to.

The following will give you output similar to get_headers, except it has a timeout, and it doesn't follow redirects:

{$ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch,CURLOPT_HEADER,true);curl_setopt($ch,CURLOPT_NOBODY,true);curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_TIMEOUT,15);$r=curl_exec($ch);$r=split("\n",$r);

return$r;

}

Ifyoudowant to follow redirects,you candosomething like this:$go=1;$i=1;

while ($go&&$i<6)

{$headers=get_headers_curl($url);$go=getNextLocation($headers);

if ($go)

{$url=modifyUrl($go);

}$i++;

}

functiongetNextLocation($headers)

{$array=$headers;$count=count($array);

for ($i=0;$i

{

if (strpos($array[$i],"ocation:"))

{$url=substr($array[$i],10);

}

}

if ($url)

{

return$url;

}

else

{

return0;

}

}?>

info at marc-gutt dot de (2008-06-21 05:04:49)

Should be the same than the original get_headers():

functionget_headers($url,$format=0) {$headers= array();$url=parse_url($url);$host= isset($url['host']) ?$url['host'] :'';$port= isset($url['port']) ?$url['port'] :80;$path= (isset($url['path']) ?$url['path'] :'/') . (isset($url['query']) ?'?'.$url['query'] :'');$fp=fsockopen($host,$port,$errno,$errstr,3);

if ($fp)

{$hdr="GET$pathHTTP/1.1\r\n";$hdr.="Host:$host\r\n";$hdr.="Connection: Close\r\n\r\n";fwrite($fp,$hdr);

while (!feof($fp) &&$line=trim(fgets($fp,1024)))

{

if ($line=="\r\n") break;

list($key,$val) =explode(': ',$line,2);

if ($format)

if ($val)$headers[$key] =$val;

else$headers[] =$key;

else$headers[] =$line;

}fclose($fp);

return$headers;

}

returnfalse;

}

}?>

php dot sirlancelot at spamgourmet dot com (2008-06-05 13:59:32)

I tried to replicate the native behavior as much as possible for systems that don't have the get_headers() function. Here it is:

functionget_headers($Url,$Format=0,$Depth=0) {

if ($Depth>5) return;$Parts=parse_url($Url);

if (!array_key_exists('path',$Parts))$Parts['path'] ='/';

if (!array_key_exists('port',$Parts))$Parts['port'] =80;

if (!array_key_exists('scheme',$Parts))$Parts['scheme'] ='http';$Return= array();$fp=fsockopen($Parts['host'],$Parts['port'],$errno,$errstr,30);

if ($fp) {$Out='GET '.$Parts['path'].(isset($Parts['query']) ?'?'.@$Parts['query'] :'')." HTTP/1.1\r\n".'Host: '.$Parts['host'].($Parts['port'] !=80?':'.$Parts['port'] :'')."\r\n".'Connection: Close'."\r\n";fwrite($fp,$Out."\r\n");$Redirect=false;$RedirectUrl='';

while (!feof($fp) &&$InLine=fgets($fp,1280)) {

if ($InLine=="\r\n") break;$InLine=rtrim($InLine);

list($Key,$Value) =explode(': ',$InLine,2);

if ($Key==$InLine) {

if ($Format==1)$Return[$Depth] =$InLine;

else$Return[] =$InLine;

if (strpos($InLine,'Moved') >0)$Redirect=true;

} else {

if ($Key=='Location')$RedirectUrl=$Value;

if ($Format==1)$Return[$Key] =$Value;

else$Return[] =$Key.': '.$Value;

}

}fclose($fp);

if ($Redirect&& !empty($RedirectUrl)) {$NewParts=parse_url($RedirectUrl);

if (!array_key_exists('host',$NewParts))$RedirectUrl=$Parts['host'].$RedirectUrl;

if (!array_key_exists('scheme',$NewParts))$RedirectUrl=$Parts['scheme'].'://'.$RedirectUrl;$RedirectHeaders=get_headers($RedirectUrl,$Format,$Depth+1);

if ($RedirectHeaders)$Return=array_merge_recursive($Return,$RedirectHeaders);

}

return$Return;

}

returnfalse;

}}?>The function will handle up to five redirects.

Enjoy!

dxtrim at yahoo dot com (2008-01-17 01:16:11)

Content-Type returns a value depending only on the extension and not the real MIME TYPE.

So, bad_file.exe renamed to good_file.doc will return application/msword

A file without extension returns a 404.

(2006-11-13 00:29:21)

I've noticed it.

Some Server will simply return the false reply header if you sent 'HEAD' request instead of 'GET'. The 'GET' request header always receiving the most actual HTTP header instead of 'HEAD' request header. But If you don't mind for a fast but risky method then 'HEAD' request is better for you.

btw ... this is get header with additional information such as User, Pass & Refferer. ...

if (!empty($user)) {$authentification=base64_encode($user.':'.$pass);$authline="Authorization: Basic$authentification\r\n";

}

if (!empty($referer)) {$refererline="Referer:$referer\r\n";

}$url_info=parse_url($url);$port= isset($url_info['port']) ?$url_info['port'] :80;$fp=fsockopen($url_info['host'],$port,$errno,$errstr,30);

if($fp) {$head="GET ".@$url_info['path']."?".@$url_info['query']." HTTP/1.0\r\n";

if (!empty($url_info['port'])) {$head.="Host: ".@$url_info['host'].":".$url_info['port']."\r\n";

} else {$head.="Host: ".@$url_info['host']."\r\n";

}$head.="Connection: Close\r\n";$head.="Accept: */*\r\n";$head.=$refererline;$head.=$authline;$head.="\r\n";fputs($fp,$head);

while(!feof($fp) or ($eoheader==true)) {

if($header=fgets($fp,1024)) {

if ($header=="\r\n") {$eoheader=true;

break;

} else {$header=trim($header);

}

if($format==1) {$key=array_shift(explode(':',$header));

if($key==$header) {$headers[] =$header;

} else {$headers[$key]=substr($header,strlen($key)+2);

}

unset($key);

} else {$headers[] =$header;

}

}

}

return$headers;

} else {

returnfalse;

}

}?>

Regards.

Donovan

(2006-05-10 04:10:17)

If you want to get headers that current PHP process is going to send back to browser, see headers_list()

stuart at sixletterwords dot com (2005-09-14 12:52:41)

hey, i came across this afew weeks ago and used the function in an app for recording info about domains that my company owns, and found that the status this returns was wrong most of the time (400 bad request or void for sites that were clearly online). then looking into it i noticed the problem was that it wasn't able to get the correct info about sites with redirections. but thats not the full problem because everything on my server was returning the wrong status too. i searched around on php.net for other info and found that fsockopen's example worked better and only needed some tweeking.

heres the function i put together from it and a small change.

functionget_headers($url,$format=0,$httpn=0){$fp=fsockopen($url,80,$errno,$errstr,30);

if ($fp) {$out="GET / HTTP/1.1\r\n";$out.="Host:$url\r\n";$out.="Connection: Close\r\n\r\n";fwrite($fp,$out);

while (!feof($fp)) {$var.=fgets($fp,1280);

}$var=explode("

return$var;

}

}

}?>

this returns an array of the header (only problem being that if the site doesn't have correct html it'll pull in some content too).

hope this'll help someone else.

sey at sey dot prometheus-designs dot net (2005-07-27 16:10:38)

The replacement updated get_headers function by aeontech at gmail dot com improperly formats dates when $format = 1.

Replace:

else {

$headers[strtolower($h2[0])] = trim($h2[1]);

}

?>

With:

else {

$foo = implode( ':', $h2 );

$foo = preg_replace( '/[a-zA-Z- ]*: /', '', $foo );

$headers[strtolower($h2[0])] = trim( $foo );

}

drfickle2 at yahoo dot com (2005-07-27 05:01:07)

aeontech, this the below change adds support for SSL connections. Thanks for the code!

if (isset($url_info['scheme']) && $url_info['scheme'] == 'https') {

$port = 443;

$fp=fsockopen('ssl://'.$url_info['host'], $port, $errno, $errstr, 30);

} else {

$port = isset($url_info['port']) ? $url_info['port'] : 80;

$fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);

}

(2005-07-15 13:37:21)

For anyone reading the previous comments, here is code that takes into account all the previous suggestions and includes a bugfix, too.

This code basically provides the "get_headers" function even on systems that are not running PHP 5.0.  It uses strtolower() on the keys, as suggested.  It uses the $h2 array instead of the $key, as suggested.  It removes a line about unsetting the $key -- no reason to unset something which is no longer used.  And I've changed the status header to be named "status" (instead of "0") in the array.  Note that if more than one header is returned without a label, they'll be stuck in "status" -- but I think status is the only header that comes back without a label, so it works for me.  So, first the code, then a sample of the usage:

* @return array

* @param string $url

* @param int $format

* @desc Fetches all the headers

* @author cpurruc fh-landshut de

* @modified by dotpointer

* @modified by aeontech

*/functionget_headers($url,$format=0) {$url_info=parse_url($url);$port= isset($url_info['port']) ?$url_info['port'] :80;$fp=fsockopen($url_info['host'],$port,$errno,$errstr,30);

if($fp) {$head="HEAD ".@$url_info['path']."?".@$url_info['query'];$head.=" HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";fputs($fp,$head);

while(!feof($fp)) {

if($header=trim(fgets($fp,1024))) {

if($format==1) {$h2=explode(':',$header);// the first element is the http header type, such as HTTP/1.1 200 OK,

// it doesn't have a separate name, so we have to check for it.if($h2[0] ==$header) {$headers['status'] =$header;

}

else {$headers[strtolower($h2[0])] =trim($h2[1]);

}

}

else {$headers[] =$header;

}

}

}

return$headers;

}

else {

returnfalse;

}

}

}?>

OK?  Here's the usage:

$response=get_headers('http://www.example.com/',1);

if (!$response) {

echo'Unable to initiate connection.';

}

else {print_r($response);

}?>

Chortos-2 (2005-06-03 02:44:26)

aeontech, I'd edit your function a little... How about replacing this:

$key = array_shift(explode(':',$header));

// the first element is the http header type, such as HTTP 200 OK,

// it doesn't have a separate name, so we have to check for it.

if($key == $header)

{

$headers[] = $header;

}

else

{

$headers[$key]=substr($header,strlen($key)+2);

}

?>

with this:

$h2 = explode(':',$header);

// the first element is the http header type, such as HTTP/1.1 200 OK,

// it doesn't have a separate name, so we have to check for it.

if($h2[0] == $header)

{

$headers[] = $header;

}

else

{

$headers[ $h2[0] ] = trim($h2[1]);

}

?>

I think it looks a bit nicer :)

david at nothisbit dot futuresbright dot com (2005-04-05 04:03:03)

After discovering that some webservers reply with "Content-Type" and others with "Content-type" I modified the function below to use strtolower($key) to make for easy checking against these case differences.

aeontech at gmail dot com (2004-12-23 17:20:18)

In response to dotpointer's modification of Jamaz' solution...

Here is a small modification of your function, this adds the emulation of the optional $format parameter.

* @return array

* @param string $url

* @param int $format

* @desc Fetches all the headers

* @author cpurruc fh-landshut de

* @modified by dotpointer

* @modified by aeontech

*/functionget_headers($url,$format=0)

{$url_info=parse_url($url);$port= isset($url_info['port']) ?$url_info['port'] :80;$fp=fsockopen($url_info['host'],$port,$errno,$errstr,30);

if($fp)

{$head="HEAD ".@$url_info['path']."?".@$url_info['query']." HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";fputs($fp,$head);

while(!feof($fp))

{

if($header=trim(fgets($fp,1024)))

{

if($format==1)

{$key=array_shift(explode(':',$header));// the first element is the http header type, such as HTTP 200 OK,

// it doesn't have a separate name, so we have to check for it.if($key==$header)

{$headers[] =$header;

}

else

{$headers[$key]=substr($header,strlen($key)+2);

}

unset($key);

}

else

{$headers[] =$header;

}

}

}

return$headers;

}

else

{

returnfalse;

}

}

}?>

php 请求 响应,PHP 取得服务器响应一个 HTTP 请求所发送的所有标头相关推荐

  1. 服务器write后客户端响应,客户端解析服务器响应的multipart/form-data数据

    multipart/form-data,多部件请求体.这个请求体比较特殊,它可以拆分为多个部件,每个部件都有自己的header和body,最常用的地方就是:客户端文件上传,因为有多个部件,在上传文件的 ...

  2. javaweb中服务器响应,Java Web服务器响应与JSON

    我想创建一个简单的Java Web应用程序响应GET请求/用JSON字符串测试.Java Web服务器响应与JSON 我的环境是Java,Intellij和Tomcat 8.5.4. 到目前为止,我有 ...

  3. pdf意外的服务器响应,浏览器及服务器响应流程.pdf

    当我们在浏览器中输入了一个URL 地址(如),从等待到页面显示的过 程中,后台究竟发生了什么处理呢? . 解析域名地址为IP 地址 浏览器DNS 缓存:以Chrome 为例,在浏览器窗口中输入 chr ...

  4. 解析远程服务器响应错误,远程服务器返回一个意外的响应:(400)错误的请求,WCF...

    远程服务器返回了意外的响应:(400)错误的请求. 一切工作正常发送到WCF和图像不是那么大〜90kb.我在这方面发现了很多线索,但没有什么能帮助我.我试图增加大小限制,但这不起作用. 的web.co ...

  5. HTTP协议、【HTTP请求、响应格式】及一次HTTP请求的完整过程

    HTTP协议及一次[请求.响应]的完整过程 HTTP协议简介 HTTP协议工作原理 一次HTTP请求的完整过程 浏览器根据域名解析IP地址 浏览器通过IP地址与WEB服务器建立一个TCP连接 浏览器给 ...

  6. 一个HTTP请求的一生

    目录 HTTP简介 HTTP传输流程 一.地址解析 域名解析: 二.封装HTTP数据包 三.封装TCP包 四.浏览器与服务建立连接 TCP/IP的三次握手 五.发起HTTP请求 HTTP请求报文结构: ...

  7. 微信小程序请求头header_微信小程序开发:http请求

    在微信小程序进行网络通信,只能和指定的域名进行通信,微信小程序包括四种类型的网络请求. 普通HTTPS请求(wx.request) 上传文件(wx.uploadFile) 下载文件(wx.downlo ...

  8. python同时同步发送多个请求_python如何实现“发送一个请求,等待多个响应”的同步?...

    我正在写一些代码通过串行口与单片机通信. MCU端基本上是一个请求/响应服务器. 一个或多个MCU发送我的请求. 然而,响应可以异步到达并且具有随机延迟,但是响应的顺序将保持不变. 另外,我的应用程序 ...

  9. get方法 服务器响应,HTTP请求方法及响应码详解(http get post head)

    HTTP是Web协议集中的重要协议,它是从客户机/服务器模型发展起来的.客户机/服务器是运行一对 相互通信的程序,客户与服务器连接时,首先,向服务器提出请求,服务器根据客户的请求,完成处理 并给出响应 ...

最新文章

  1. 图书管理系统python怎么保存用户注册信息_Python实现图书管理系统
  2. s7day2学习记录
  3. MySQL索引知识总结
  4. GO关于gin工程关联GOPATH的说明
  5. API Gateway简介
  6. 随机值获取—random
  7. SQLSERVER 日志收缩
  8. leetcode165. 比较版本号 超级重要的细节
  9. 九度OJ 1037:Powerful Calculator(强大的计算器) (大整数运算)
  10. 第2章 神经网络的数学基础
  11. 徐松亮硬件教学-微波天线设计-基于HFSS软件的天线设计流程
  12. 电子证件照尺寸怎样裁剪?怎么把照片裁剪成2寸?
  13. 云开发地铁路线图小程序源码和配置教程
  14. 服务器gpt安装系统bios设置,系统安装的两种模式:UEFI+GPT、BIOS+MBR-网络教程与技术 -亦是美网络...
  15. flutter混编ios打包生成ipa文件
  16. 阿里通信携手联通MWC演示“智选加速” 预演5G垂直应用
  17. python使用selenium模拟浏览器进入好友QQ空间留言
  18. 失控的摄像头,谁是窥视者!
  19. Error handling response: TypeError: Cannot read property ‘1‘ of null
  20. 小程序errno_错误:UNIX程序中的errno

热门文章

  1. 最好的jpg转换pdf软件
  2. ons模拟器 linux,ons模拟器
  3. 泰斗破坏神(一)登陆界面的制作
  4. [python][企业微信]企业微信自动打卡Python脚本,价值一万元的自动打卡脚本
  5. 【离散数学期复习系列】二、一阶逻辑(谓词逻辑)
  6. linux的wget命令
  7. 轻松关闭QQ2007迷你首页
  8. 【LaTex】\begin{array}{r},\begin{array}{l},\begin{array}{c}
  9. 实验记录 | 6/7 收一下尾巴
  10. 【微信小程序】页面导航详解