2013-02-20 145 views
10

我正在编写一个属性门户网站。我被困在检查图像。我知道如何检查是否设置了图片网址。但问题是检测在url上是否有实际的有效图像。检查图像是否存在php

例如: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存在,它确实有事先只是没有像有

感谢

+0

也许你可以看看在返回的HTML标签的物理路径? – silkfire 2013-02-20 00:41:40

+0

我在想,但页面是相当大的一种想要做的一切,在飞行中使用PHP – 2013-02-20 00:44:15

+0

你可以发布一个链接到_does_存在的图像? – silkfire 2013-02-20 00:46:49

回答

24

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

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

这对于外部URI来说非常慢。 – pltvs 2013-07-12 10:45:28

+0

如果文件不存在,它会导致php通知。使用这个功能与“@”是不好的方式,所以我认为更好的方式是@ plutov.by描述 – Vaha 2017-01-26 09:52:36

+0

@Vaha注意但是,plutov的答案不会做这个答案,它只检查一个特定的URL是否存在。 – 2017-01-26 10:01:25

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

可以use file_exists功能检查,如果图像存在,但你应该给图像

if (file_exists(dirname($_SERVER['SCRIPT_FILENAME']).'/'.$filename))   
{ 
    // your code here 
}