【问题标题】:Is there a way to check whether a remote image is exist? PHP有没有办法检查远程图像是否存在? PHP
【发布时间】:2012-02-14 02:40:02
【问题描述】:

我的网站在 LAMP 中运行,我的图片 CDN 在 nginx 中。

我想做的是: 检查请求的图像在 CDN 服务器中是否有副本,如果有则将副本借给 CDN 服务器,否则为用户加载本地副本。

是否有以编程方式检查远程 CDN 图像是否存在?

(也许确定标头?因为我注意到如果请求图像不存在,则返回 404)

【问题讨论】:

标签: php nginx cdn


【解决方案1】:

只要副本是公开的,您就可以使用 cURL 检查 404。 See this question 详细说明如何操作。

【讨论】:

    【解决方案2】:

    我用这个方法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 已禁用它。

    【讨论】:

      【解决方案3】:

      您可以为此使用 file_get_contents:

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

      还有一件事——如果你只想显示带有 img 标签的图像,你可以简单地这样做——使用 img 标签 onerror 属性——如果图像在服务器上不存在,onerror 属性将显示本地文件:

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

      您可以在此处阅读类似的问题:detect broken image using php

      【讨论】:

      • 是的,但这取决于他想对图像做什么。如果他只是想显示它,我已经用一种使用简单 html 的方式更新了我的答案,而无需执行任何头文件或文件是否存在检查
      【解决方案4】:

      另一种更简单的方法 - 没有 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 方法可以被服务器管理员禁用,但在受控环境中它是最好的方法。
      • header方法是否也加载图片内容?
      • @gilzero 不,函数仅获取标题。
      【解决方案5】:
      <?php
      if (is_array(getimagesize("http://www.imagelocation.com/image.png"))){
         // Image ok
      } else {
         // Image not ok
      }
      ?>
      

      【讨论】:

      • 这会将整个图像从 CDN 下载到网络服务器,不必要地增加两个服务器的负载。
      猜你喜欢
      • 1970-01-01
      • 2012-05-16
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      • 2023-03-31
      • 2010-11-24
      相关资源
      最近更新 更多