2014-09-12 124 views
0

我有這樣的腳本:只顯示圖片

$uploadsDirectory = dirname($_SERVER['SCRIPT_FILENAME']) .'/slides/head/'; 
if ($handle = opendir($uploadsDirectory)) { 
    $uplo = array(); 
while (false !== ($file = readdir($handle))) { 
    array_push($uplo, $file);} 
    sort($uplo,SORT_NATURAL | SORT_FLAG_CASE); 
    $user = array(); 
foreach($uplo as $fname) { 
if($fname != ".." && $fname != "."){ 
if(substr($fname,0,1) != "_") 
    echo "<div class='bgitem' id='head'>$fname</div>"; 
else 
    array_push($user, "$fname");}} 
    closedir($handle);} 

它工作正常,但我怎樣才能使它所以只顯示圖片? (我有沒有其他的照片文件,因此它會顯示一個破碎的圖片來代替。)

+0

爲什麼不把過濾器陣列可以接受的擴展? – Rasclatt 2014-09-12 16:57:19

+3

'if($ fname是圖片){顯示它}' – 2014-09-12 16:57:21

回答

0

解決方案爲您提供:

$extension = explode(".", $fname); 
$extension = (isset($extension) && count($extension) > 0)?strtolower($extension[count($extension) -1]):null; 

if(in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])){ 
    //Show the image 

}else{ 
    //dont show image 
} 
0

一個簡單的辦法是把它測試文件是否是一個圖像在同一行中測試文件是父目錄還是當前目錄(if($fname != ".." && $fname != "."){

您可以使用getimagesize()來確定文件是否爲任何類型的圖像。如果它不是圖像,它將返回零。

$uploadsDirectory = dirname($_SERVER['SCRIPT_FILENAME']) .'/slides/head/'; 
if ($handle = opendir($uploadsDirectory)) { 
    $uplo = array(); 
while (false !== ($file = readdir($handle))) { 
    array_push($uplo, $file);} 
    sort($uplo,SORT_NATURAL | SORT_FLAG_CASE); 
    $user = array(); 
foreach($uplo as $fname) { 
if($fname != ".." && $fname != "." && getimagesize($fname) != 0){ //Tests if file is an iamge 
if(substr($fname,0,1) != "_") 
    echo "<div class='bgitem' id='head'>$fname</div>"; 
else 
    array_push($user, "$fname");}} 
    closedir($handle);}