检查图片是否存在 PHP

13

我正在编写一个房地产门户网站,卡在了检查图片上。我知道如何检查是否设置了图像URL,但问题是如何检测该URL上是否实际存在有效的图像。

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

这个图像URL存在,但实际上已被删除,所以在我的房产搜索页面上只会显示空白。有没有办法检查URL上是否有图像,如果不存在,则显示占位符。

类似于:

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

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

但这只是检查URL是否存在,而实际上存在,只是没有图片。

提前感谢。


也许你可以在返回的 HTML 中查找 <img> 标签? - silkfire
我曾经考虑过这个,但页面相当大,我想用PHP实时完成所有操作。 - Barry Connolly
你能够贴出一张确实存在的图片链接吗? - silkfire
3个回答

28

使用getimagesize()函数来确保URL指向有效的图像。

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

8
对于外部 URI,它的功能非常缓慢。 - Alex Pliutau
如果文件不存在,它会导致PHP Notice。在使用此函数时加上"@"符号是不好的习惯,因此我认为更好的方法是像@plutov.by所描述的那样。 - Vaha

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

1
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';
}

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