![](/img/trans.png)
[英]Showing files from multiple directories which all have different file names and display in table PHP
[英]PHP Count through different directories and see which ones have 0 files in them
我具有以下文件夾結構:
images/photo-gallery/2e/
72/
rk/
u3/
va/
yk/
... 等等。 基本上,每次上傳圖像時,它都會對名稱進行哈希處理,然后使用前兩個字母創建一個文件夾。 所以2e內部是2e0gpw1p.jpg
這就是事情...如果我刪除圖像,它將刪除文件,但會保留其所在的文件夾。現在,當我上傳了大量圖像時,這很好,因為許多圖像共享相同的圖像文件夾..但直到那時,我最終將擁有一堆空目錄。
我想做的是搜索相冊文件夾,並遍歷每個目錄,看看哪些文件夾是空的。如果有任何空文件夾,它將刪除它。
我知道如何對單個目錄(例如2e文件夾)執行此操作。 但是,如何處理相冊文件夾中的所有文件夾呢?
如果目錄不為空,PHP函數rmdir()將引發警告,因此您可以在非空目錄上使用它,而不必擔心將其刪除。 將其與scandir()和array_slice結合(以刪除。和..),可以執行以下操作:
foreach(array_slice(scandir('images/photo-gallery'),2) as $dir) {
@rmdir('images/photo-gallery/' . $dir); // use @ to silence the warning
}
雖然您可以使用php進行處理,但我傾向於將os用於此類任務。 當然,您可以使用php調用以下內容
find <parent-dir> -depth -type d -empty -exec rmdir -v {} \;
請閱讀此警告,但我並未嘗試使用類似次數的代碼。 如果您不了解這樣做的意思,那就不要使用它,否則有可能從服務器上擦除您的網站。
第一次嘗試之前,請進行所有備份編輯,路徑非常重要!
好的,這很簡單:)
<?php
function recursiveDelete($path){
$ignore = array(
'cgi-bin',
'.',
'..'
); // Directories to ignore
$dh = opendir($path); // Open the directory
while(false !== ($file = readdir($dh))){ // Loop through the directory
if(!in_array($file, $ignore)){ // Check that this file is not to be ignored
if(is_dir($path."/".$file)){ // Its a directory, keep going
if(!iterator_count(new DirectoryIterator($path."/".$file)))
rmdir($path."/".$file); // its empty delete it
} else {
recursiveDelete($path."/".$file);// Recursive call to self
}
}
}
}
closedir($dh); // All Done close the directory
}
// WARNING IMPROPERLY USED YOU CAN DUMP YOUR ENTIRE SERVER USE WITH CAUTION!!!!
// I WILL NOT BE HELD RESPONSIBLE FOR MISUSE
recursiveDelete('/some/directoy/path/to/your/gallery');
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.