【问题标题】:How to check if Image exists on server using URL如何使用 URL 检查图像是否存在于服务器上
【发布时间】:2013-08-05 19:41:54
【问题描述】:

我正在尝试检查服务器上是否存在图像文件。我正在获取其他服务器的图像路径。

请检查下面我尝试过的代码,

$urlCheck = getimagesize($resultUF['destination']);

if (!is_array($urlCheck)) {
  $resultUF['destination'] = NULL;
}

但是,它显示在警告下方

Warning: getimagesize(http://www.example.com/example.jpg) [function.getimagesize]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in

有什么办法吗?

谢谢

【问题讨论】:

  • 你需要提供像“images/example.jpg”这样的绝对路径
  • @MakC 任何答案有帮助吗?
  • @sankalpMishra 是的,我尝试了以下答案,但由于 allow_url_fopen 它在服务器上显示警告,所以我尝试使用 CURL,它对我有用。
  • @PravinS 我不能使用绝对路径,因为我的图像文件在另一台服务器上,而我的代码在另一台服务器上
  • @MakC 使用 get_headers() 函数,它会返回你的长度,http响应等等

标签: php


【解决方案1】:
$url = 'http://www.example.com/example.jpg)';
print_r(get_headers($url));

它会给出一个数组。现在您可以检查响应以查看图像是否存在

【讨论】:

    【解决方案2】:

    您需要检查该文件是否在服务器上定期存在。您应该使用:

    is_file.例如

    $url="http://www.example.com/example.jpg";

    if(is_file($url))
    {
    echo "file exists on server";
    }
    else
    {
    echo "file not exists on server ";
    }
    

    【讨论】:

      【解决方案3】:

      最快速有效的解决损坏或找不到图片链接的方法
      我建议你不要使用 getimagesize() 因为它会第一次下载图像然后它会检查图像大小+如果这不会图像那么它会抛出异常所以使用下面的代码

      if(checkRemoteFile($imgurl))
      {
      //found url, its mean
      echo "this is image";
      }
      
      function checkRemoteFile($url)
      {
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL,$url);
          // don't download content
          curl_setopt($ch, CURLOPT_NOBODY, 1);
          curl_setopt($ch, CURLOPT_FAILONERROR, 1);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          if(curl_exec($ch)!==FALSE)
          {
              return true;
          }
          else
          {
              return false;
          }
      }
      

      注意: 此当前代码可帮助您识别损坏或未找到的 url 图像这不会帮助您识别图像类型或标题

      【讨论】:

        【解决方案4】:

        使用fopen函数

        if (@fopen($resultUF['destination'], "r")) {
            echo "File Exist";
        } else {
            echo "File Not exist";
        }
        

        【讨论】:

          【解决方案5】:

          问题是图片可能不存在或者您没有直接权限来访问该图片,否则您必须指向无效的位置到图片。

          【讨论】:

            【解决方案6】:

            您可以使用file_get_contents。这将导致 php 在返回 false 的同时发出警告。您可能需要处理此类警告显示,以确保用户界面不会与之混淆。

             if (file_get_contents($url) === false) {
                   //image not foud
               }
            

            【讨论】:

            猜你喜欢
            • 2013-09-21
            • 2014-12-12
            • 1970-01-01
            • 2015-02-16
            • 1970-01-01
            • 2010-11-30
            • 2014-06-27
            • 1970-01-01
            • 2012-03-01
            相关资源
            最近更新 更多