background image

 

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

要确定一个文件在远端服务器上是否存在,只需要确定访问这个文件返回的状态码

”HTTP/1.1 200 OK”就可以了。

当然,也可以判断状态码不是

”HTTP/1.1 404 Not Found”则文件存在,不过总感觉不保险,

毕竟还有其它的诸如

301,400 这类的状态码。

获取三位

HTTP 响应码的例子:

代码如下

:

<?php 
function get_http_response_code($theURL) { 
    $headers = get_headers($theURL); 
    return substr($headers[0], 9, 3); 
}
?>
get_headers 的作用就是访问一个远程地址,把服务器发送的 HTTP 头以数组形式返回。而
$header[0]则是服务器返回的状态码(如果不出意外的话状态码应该都是第一个返回的)。
排除重定向的例子
代码如下

:

<?php
/**
 * Fetches all the real headers sent by the server in response to a HTTP request without redirects
 * 获取不包含重定向的报头
 */
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