2013-02-20 204 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 
}