Is there a way to check whether a remote image is exist? PHP Is there a way to check whether a remote image is exist? PHP nginx nginx

Is there a way to check whether a remote image is exist? PHP


I use this method to ping distant files:

  /**   * Use HTTP GET to ping an url   *   * /!\ Warning, the return value is always true, you must use === to test the response type too.   *    * @param string $url   * @return boolean true or the error message   */  public static function pingDistantFile($url)  {    $options = array(      CURLOPT_FOLLOWLOCATION => true,      CURLOPT_URL => $url,      CURLOPT_FAILONERROR => true, // HTTP code > 400 will throw curl error    );    $ch = curl_init();    curl_setopt_array($ch, $options);    $return = curl_exec($ch);    if ($return === false)    {      return curl_error($ch);    }    else    {      return true;    }  }

You can also use the HEAD method but maybe your CDN as disabled it.


So long as the copy is public, you could just check for a 404 with cURL. See this question detailing how to do it.


You can use file_get_contents for this:

 $content = file_get_contents("path_to_your_remote_img_file"); if ($content === FALSE) {     /*Load local copy*/ } else {     /*Load $content*/ }

Oh and one more thing- if you only want to display the image with an img tag, you can simply do this- using img tags onerror attribute- if the image does not exist on the server, the onerror attribute will display the local file:

<img src="path_to_your_remote_img_file" onerror='this.src="path_to_your_local_img_file"'>

You can read a similar question on this here: detect broken image using php