如何使用URL检查服务器上是否存在图像


How to check if Image exists on server using URL

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

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

$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

有什么办法吗?

感谢

$url = 'http://www.example.com/example.jpg)';
print_r(get_headers($url));

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

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

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 ";
}

最快&损坏或找不到图像的高效解决方案链接
我建议你不要使用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图像这将无法帮助您识别图像类型或标题

使用fopen函数

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

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

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

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