天天看点

PHP检测远端文件是否存在

PHP检测远端文件是否存在

<?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"的话则文件存在,不过总感觉不保险,毕竟还有其他的诸如301,400这类的状态码)。

<code>获取三位http响应码的例子:</code>

PHP检测远端文件是否存在

function get_http_response_code($theurl) {  

    $headers = get_headers($theurl);  

    return substr($headers[0], 9, 3);  

}  

?&gt;   

 排除重定向的例子:

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' =&gt;  

        array('max_redirects'=&gt;1,'ignore_errors'=&gt;1)  

    );  

    stream_context_get_default($opts);  

  }  

  //get headers  

    $headers=get_headers($url,$format);  

    //restore default options  

  if (isset($opts)) {  

        array('max_redirects'=&gt;20,'ignore_errors'=&gt;0)  

  //return  

    return $headers;  

?&gt;