get_headers()是PHP5以后增加的一个函数,用来取得服务器响应一个 HTTP 请求所发送的所有标头。
get_headers(string $url, int $format = 0): array
get_headers() 返回一个数组,包含有服务器响应一个 HTTP 请求所发送的标头。$url是待转换的网址,format是可选的,默认是0,如果设置成1的话, get_headers() 会解析相应的信息并设定数组的键名。
例如:
<?php $url = 'http://www.example.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
)
获取真实的URL
下面的代码首先用get_headers函数获取http标头,然后判断是否存在临时跳转(301,302),再判断标头信息是否数组,然后按不同的方式获取这是URL。最后,如果没有跳转,则返回原始地址。
function getRealURL($url){
$header = get_headers($url,1);
if (strpos($header[0],'301') || strpos($header[0],'302')) {
if(is_array($header['location'])) {
return $header['location'][count($header['location'])-1];
}else{
return $header['location'];
}
}else {
return $url;
}
}值得注意的:PHP是大小写敏感的,函数中的参数不能写错。
更好的方案
上面代码是有问题的。在实际工作中,服务器返回的header信息并不统一,location字段,有的首字母大写了,有的是小写的。所以以上代码在某些url处理时并不能正常工作。针对此问题,建议改成下面这样。
function getRealURL($url){
$header = get_headers($url);
// 如果返回头部信息第一个字段中含有301或302
if (strpos($header[0],'301') || strpos($header[0],'302')) {
return substr($header[5],10);
}else {
return $url;
}
}对于301或302临时跳转来说,头部信息的第五个就是locaiton,直接截取后面的字符串就好了。还有就是get_headers函数的第二个参数要去掉。