2012-03-12 39 views
0

我的目錄結構如下所示。檢查縮略圖是否存在於PHP

...photo-album1/ 
...photo-album1/thumbnails/ 

比方說我們有image1.jpgphoto-album1/。這個文件的縮略圖是tn_image1.jpg

我想要做的是檢查photo-album1/裏面的每個文件,如果他們有縮略圖在photo-album1/thumbnails/。如果他們只是繼續,如果沒有,發送文件名到另一個功能:generateThumb()

我該怎麼做?

+0

水珠()來獲取目錄列表,的foreach()循環,file_exists()來檢查 – 2012-03-12 19:56:53

+4

[?你嘗試過什麼(http://mattgemmell.com/2008/ 12/08/what-you-you-tried /) – j08691 2012-03-12 20:00:12

+0

@ j08691腳本非常長,在這裏發帖 – heron 2012-03-12 20:02:26

回答

1
$dir = '/my_directory_location'; 
$files = scandir($dir);//or use 
$files =glob($dir); 
foreach($files as $ind_file){ 
if (file_exists($ind_file)) { 
    echo "The file $filexists exists"; 
    } else { 
    echo "The file $filexists does not exist"; 
    } 

} 
+0

那是什麼?大聲笑。我知道file_exists()函數。問題是我無法弄清楚如何從父目錄中一個一個地獲取文件,並檢查縮略圖中的thum使用foreach循環的目錄 – heron 2012-03-12 20:00:52

+0

?併發布你的代碼? rofl沒有它沒有可以給一個解決方案 – Ghostman 2012-03-12 20:01:33

0

簡單的方法是使用PHP的glob功能:

$path = '../photo-album1/*.jpg'; 
$files = glob($path); 
foreach ($files as $file) { 
    if (file_exists($file)) { 
     echo "File $file exists."; 
    } else { 
     echo "File $file does not exist."; 
    } 
} 

感謝靈魂上面的基本知識。我只是將glob添加到它。

編輯:正如hakre指出的那樣,glob只會返回現有文件,因此您可以通過檢查文件名是否在數組中來加速它。喜歡的東西:

if (in_array($file, $files)) echo "File exists."; 
+0

喲歡迎... :) – Ghostman 2012-03-12 20:11:45

+1

嗯,不是隻返回現有的文件? ;) – hakre 2012-03-12 20:14:51

+0

哈,好點,好。 :) – Jemaclus 2012-03-12 20:17:40

3
<?php 

$dir = "/path/to/photo-album1"; 

// Open directory, and proceed to read its contents 
if (is_dir($dir)) { 
    if ($dh = opendir($dir)) { 
    // Walk through directory, $file by $file 
    while (($file = readdir($dh)) !== false) { 
     // Make sure we're dealing with jpegs 
     if (preg_match('/\.jpg$/i', $file)) { 
     // don't bother processing things that already have thumbnails 
     if (!file_exists($dir . "thumbnails/tn_" . $file)) { 
      // your code to build a thumbnail goes here 
     } 
     } 
    } 
    // clean up after ourselves 
    closedir($dh); 
    } 
}