PHP detects if a remote file exists

Source: Internet
Author: User
Tags response code
<?php

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

$hander _array = get_headers ($url);

if ($header _array [0] = = ' http/1.1 OK ') {

echo ' file exists ';

} else {

Echo ' file does not exist ';

}

Simply explain the above code. The function of get_headers is to access a remote address and return the HTTP headers sent by the server as an array. The $header[0] is the status code returned by the server (the status code should be the first to return if not unexpectedly).

To determine the existence of a file on the remote server, just make sure that the status code returned by accessing the file is "http/1.1" (of course you can also tell if the status code is not "http/1.1 404 Not Found" Then the file exists, but the total feeling is not insured, There are, after all, other status codes such as 301,400.

Get an example of a three-bit HTTP response code:

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

Examples of excluding redirects:

<?php  /**  * Fetches all the real headers sent by the server in response to a HTTP request without redirects
  
   * gets a header that does not contain a redirect  */     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;  }  ? >
  
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.