PHP get_headers函数作用与参数解析
get_headers() 属于 PHP 的系统内置函数,其功能是生成一个数组,其中包含了服务器针对特定 HTTP 请求所返回的所有标头信息。当请求处理失败时,该函数会返回 FALSE,同时抛出一条 E_WARNING 级别的警告信息,开发者可以利用这一返回值机制来简易判断远程资源是否可用。
函数定义
array get_headers ( string $url [, int $format = 0 ] )
参数说明
url:指定需要获取标头信息的目标 URL 地址。
format:这是一个可选参数。若将其值设置为 1,get_headers() 将对返回的信息进行解析,并将数组的键名设定为对应的标头名称,而非默认的索引数字。
代码示例
<?php
$url='http://www.phpernote.com';
print_r(get_headers($url));
print_r(get_headers($url,1));
?>
上述例程执行后的输出结果大致如下所示:
Array ( [0] => HTTP/1.1 200 OK [1] => Date: Sat, 29 May 2004 12:28:13 GMT [2] => Server: Apache/1.3.27 (Unix) (Red-Hat/Linux) [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT [4] => ETag: "3f80f-1b6-3e1cb03b" [5] => Accept-Ranges: bytes [6] => Content-Length: 438 [7] => Connection: close [8] => Content-Type: text/html )
Array ( [0] => HTTP/1.1 200 OK [Date] => Sat, 29 May 2004 12:28:14 GMT [Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux) [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT [ETag] => "3f80f-1b6-3e1cb03b" [Accept-Ranges] => bytes [Content-Length] => 438 [Connection: close [Content-Type] => text/html )