有没有一种方法可以检查远程图片是否存在?PHP

3

我的网站运行在LAMP环境下,我的图片CDN使用的是nginx。

我想要做的是:检查请求的图片是否有一个副本存储在CDN服务器上,如果有则借用CDN服务器上的副本,否则为用户加载本地副本。

是否有编程方式来检查远程CDN图片是否存在?(也许可以通过判断响应头来确定,因为我注意到如果请求的图片不存在,它会返回404错误)

在此输入图片描述


可能是检查远程URL上是否存在图像的重复问题。 - Gordon
你所说的“load”是什么意思.. 你想使用 <img></img> 展示图片吗? - Ninja
5个回答

3

我使用这种方法来ping远程文件:

  /**
   * 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;
    }
  }

你也可以使用 HEAD 方法,但是可能你的CDN已经禁用了它。

2
只要副本是公开的,您可以使用cURL检查404。请参阅此问题,详细说明如何执行此操作:查看此问题

2
您可以使用file_get_contents来实现这一点:
 $content = file_get_contents("path_to_your_remote_img_file");
 if ($content === FALSE)
 {
     /*Load local copy*/
 }
 else
 {
     /*Load $content*/
 }

还有一件事- 如果您只想使用img标签显示图像,可以简单地使用onerror属性- 如果服务器上不存在该图像,则onerror属性将显示本地文件:

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

您可以在此处阅读类似的问题:使用PHP检测损坏的图像

是的,但这取决于他想用这个图像做什么。如果他只想显示它,我已经更新了我的答案,提供了一种使用简单HTML的方法,而不必进行任何标题或文件存在检查。 - Ninja

1

另一种更简单的方法 - 不需要使用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
}

HEAD方法可以被服务器管理员禁用,但在受控环境中它是最好的方法。 - Damien
头部方法是否也会加载图像内容? - gilzero
@gilzero 不是的,函数仅获取头部信息。 - kuboslav

-1
<?php
if (is_array(getimagesize("http://www.imagelocation.com/image.png"))){
   // Image ok
} else {
   // Image not ok
}
?>

这将从CDN下载整个图像到Web服务器,不必要地增加了两个服务器的负载。 - WesleyE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接