检查图像是否存在 php

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14970322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:17:26  来源:igfitidea点击:

check if image exists php

php

提问by Barry Connolly

I am in the middle of coding up a property portal. I am stuck on checking images. I know how to check if an image url is set. But the problem is detecting if there is actually a valid image at the url.

我正在编写一个属性门户。我坚持检查图像。我知道如何检查是否设置了图像 url。但问题是检测 url 上是否确实存在有效图像。

example : http://property.images.themovechannel.com/cache/7217/6094437/img_main.jpg

示例:http: //property.images.themovechannel.com/cache/7217/6094437/img_main.jpg

This image url exists but the image is has now been removed so it just displays blank in my propety search page. Is there a way of checking there is an image there at the url and then displaying a placeholder if it doesnt exist.

此图片 url 存在,但该图片现已被删除,因此它仅在我的属性搜索页面中显示为空白。有没有办法检查 url 中是否有图像,然后在它不存在时显示占位符。

something like

就像是

$imageURL = "http://property.images.themovechannel.com/cache/7217/6094437/img_main.jpg";

if (exists($imageURL)) { display image } 
else { display placeholder }

But all this does is check the url exists, which it does there is just no image there

但所有这些都是检查 url 是否存在,它确实没有图像

Thanks in advance

提前致谢

回答by user703016

Use getimagesize()to ensure that the URL points to a valid image.

使用getimagesize()以确保网址指向有效的图像。

if (getimagesize($imageURL) !== false) {
    // display image
}

回答by Alex Pliutau

function exists($uri)
{
    $ch = curl_init($uri);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $code == 200;
}

回答by Abdo-Host

function is_webUrl($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;
    }
}

if(is_webUrl('http://www.themes.tatwerat.com/wp/ah-personal/wp-content/uploads/2016/08/features-ah-wp-view.jpg')) {
   echo 'yes i found it';
}else{
   echo 'file not found';
}