Home  >  Article  >  Backend Development  >  PHP检测远端资料是否存在

PHP检测远端资料是否存在

WBOY
WBOYOriginal
2016-06-13 13:08:07847browse

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这类的状态码)。

<span class="html"><span class="keyword">获取三位HTTP响应码的例子:</span> </span>

<?php function get_http_response_code($theURL) {
    $headers = get_headers($theURL);
    return substr($headers[0], 9, 3);
}
?> 

?排除重定向的例子:

<?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
    return $headers;
}
?> 
?
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn