Home >Backend Development >PHP Tutorial >PHP detects whether remote file exists

PHP detects whether remote file exists

巴扎黑
巴扎黑Original
2016-11-24 15:15:54998browse

$url = 'http://example.com';

$hander_array = get_headers ( $url );

if ($header_array [0] == 'HTTP/1.1 200 OK') {

echo 'File exists';

} else {

echo 'File does not exist';

}

Briefly explain the above code. The function of get_headers is to access a remote address and return the HTTP headers sent by the server in the form of an array. And $header[0] is the status code returned by the server (if nothing else happens, the status code should be the first one returned).

To confirm that a file exists on the remote server, just make sure that the status code returned by accessing the file is "HTTP/1.1 200 OK" (of course you can also determine if the status code is not "HTTP/1.1 404 Not Found" ", the file exists, but it always feels unsafe. After all, there are other status codes such as 301, 400).

Example of obtaining three-digit HTTP response code:

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

Example of excluding redirection:

<?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(&#39;http&#39; =>  
        array(&#39;max_redirects&#39;=>1,&#39;ignore_errors&#39;=>1)  
    );  
    stream_context_get_default($opts);  
  }  
  //get headers  
    $headers=get_headers($url,$format);  
    //restore default options  
  if (isset($opts)) {  
    $opts = array(&#39;http&#39; =>  
        array(&#39;max_redirects&#39;=>20,&#39;ignore_errors&#39;=>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