本文介绍下,一个使用php中的get_headers函数检测远端文件是否存在的例子,深入学习下get_headers的用法,有需要的朋友参考下。 例子,get_headers函数检测远程文件是否存在。代码: 复制代码…,
本文介绍下,一个使用php中的get_headers函数检测远端文件是否存在的例子,深入学习下get_headers的用法,有需要的朋友参考下。
例子,get_headers函数检测远程文件是否存在。
代码:
<?php $url = 'http://example.com'; $hander_array = get_headers ( $url ); if ($header_array [0] == 'HTTP/1.1 200 OK') { echo '文件存在'; } else { echo '文件不存在'; }
说明:
get_headers函数的作用:当访问一个远程地址,把服务器发送的HTTP头以数组形式返回。
而$header[0]则是服务器返回的状态码(状态码一般是第一个返回的)。
因此,要确定一个文件在远端服务器上存在,只需要确定访问这个文件返回的状态码是”HTTP/1.1 200 OK”即可。
也可以通过判断状态码不是”HTTP/1.1 404 Not Found”,也可以给出文件存在的解答。
下面再分享二个get_headers函数的例子,供大家参考。
1,获取三位HTTP响应码的例子:
<?php function get_http_response_code($theURL) { $headers = get_headers($theURL); return substr($headers[0], 9, 3); } ?>
2,排除重定向的例子:
<?php /** * 获取不包含重定向的报头 * by www.90codes.com */ function get_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 options if (isset($opts)) { $opts = array('http' => array('max_redirects'=>20,'ignore_errors'=>0) ); stream_context_get_default($opts); } //return return $headers; } ?>
附,php get_headers()
get_headers
(PHP 5)
get_headers 取得服务器响应一个 HTTP 请求所发送的所有标头
说明
array get_headers ( string $url [, int $format ] )
get_headers() 返回一个数组,包含有服务器响应一个 HTTP 请求所发送的标头。如果失败则返回 FALSE 并发出一条 E_WARNING 级别的错误信息。
如果将可选的 format 参数设为 1,则 get_headers() 会解析相应的信息并设定数组的键名。
说明:
自 PHP 5.1.3 起本函数使用默认的流上下文,其可以用 stream_context_get_default() 函数设定和修改。
get_headers()的例子:
<?php $url = 'http://www.90codes.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 )