有没有办法检查远程图像是否存在? PHP

My site is running in LAMP, my image CDN is in nginx.

I want to do is: Check if a requested image has a copy in CDN server, if yes then loan the copy in cdn server, otherwise, load the local copy for user.

Is there a programmatically way to check whether the remote CDN image is exist?

(perhaps determine the header? as I notice that if request image isn't exist, it returns 404)

enter image description here

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

Another easier way – without cURL:

$headers = get_headers('http://example.com/image.jpg', 1);
if($headers[0] == 'HTTP/1.1 200 OK')
{
  //image exist
}
else
{
  //some kind of error
}
<?php
if (is_array(getimagesize("http://www.imagelocation.com/image.png"))){
   // Image ok
} else {
   // Image not ok
}
?>