PHP get_headers检测远端文件是否存在的方法

原创
2016-07-25 08:56:04 840浏览
  1. $url = 'http://example.com';
  2. $hander_array = get_headers ( $url );
  3. if ($header_array [0] == 'HTTP/1.1 200 OK') {
  4. echo '文件存在';
  5. } else {
  6. echo '文件不存在';
  7. }
复制代码

说明: get_headers函数的作用:当访问一个远程地址,把服务器发送的HTTP头以数组形式返回。 而$header[0]则是服务器返回的状态码(状态码一般是第一个返回的)。 因此,要确定一个文件在远端服务器上存在,只需要确定访问这个文件返回的状态码是"HTTP/1.1 200 OK"即可。 也可以通过判断状态码不是"HTTP/1.1 404 Not Found",也可以给出文件存在的解答。

下面再分享二个get_headers函数的例子,供大家参考。

1,获取三位HTTP响应码的例子:

  1. function get_http_response_code($theURL) {
  2. $headers = get_headers($theURL);
  3. return substr($headers[0], 9, 3);
  4. }
  5. ?>
复制代码

2,排除重定向的例子:

  1. /**
  2. * 获取不包含重定向的报头
  3. * by bbs.it-home.org
  4. */
  5. function get_real_headers($url,$format=0,$follow_redirect=0) {
  6. if (!$follow_redirect) {
  7. //set new default options
  8. $opts = array('http' =>
  9. array('max_redirects'=>1,'ignore_errors'=>1)
  10. );
  11. stream_context_get_default($opts);
  12. }
  13. //get headers
  14. $headers=get_headers($url,$format);
  15. //restore default options
  16. if (isset($opts)) {
  17. $opts = array('http' =>
  18. array('max_redirects'=>20,'ignore_errors'=>0)
  19. );
  20. stream_context_get_default($opts);
  21. }
  22. //return
  23. return $headers;
  24. }
  25. ?>
复制代码

附,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()的例子:

  1. $url = 'http://bbs.it-home.org';
  2. print_r(get_headers($url));
  3. print_r(get_headers($url, 1));
  4. ?>
复制代码

输出类似于:

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 )



声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。