2012-10-19 128 views
0

我已經設置了一些PHP來刪除一個目錄,它的內容,以及任何子目錄及其內容...我是PHP新手,所以我肯定是在做一些錯誤或者是錯誤的以最低效的方式做事。刪除目錄內容和子目錄內容

尋找關於如何做到這一點更好......

順便說一些參考或建議,該代碼工作正常。使用PHP 5.3.8。

chmod($main_dir, 0755); 
if ($handle = opendir($main_dir)) { 
    while (false !== ($entry = readdir($handle))) { 
     $absolute_path = $main_dir.'/'.$entry; 
     if ($entry != "." && $entry != "..") {  
      chmod($absolute_path, 0755); 
      unlink($absolute_path); 

      //check if any folders exist, then delete files within 
      if (file_exists($absolute_path) && is_dir($absolute_path)) { 
       if ($child_handle = opendir($absolute_path)) { 
        while (false !== ($child_entry = readdir($child_handle))) {    
        $child_absolute_path = $absolute_path.'/'.$child_entry; 
         if ($child_entry != "." && $child_entry != "..") {    
          chmod($child_absolute_path, 0755); 
          unlink($child_absolute_path); 
         } 
        } 
        closedir($child_handle); 
       } 
      } 
      rmdir($absolute_path); 
     } 
    } 
    closedir($handle); 
} 
rmdir($main_dir); 

有什麼想法?非常感激! 即時通訊使用PHP 5.3.8

+0

這可能是在[代碼審查]更合適(http://codereview.stackexchange.com/?as=1) – noel

+0

@shakabra謝謝,現在要去看看...... – Terry

回答

4

您可以使用RecursiveDirectoryIterator列出所有文件和文件夾,然後刪除它們。請注意,您必須使用RecursiveIteratorIterator::CHILD_FIRST,以便在文件夾之前刪除文件。

$dir = __DIR__ . "/test"; 
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); 
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST); 
foreach ($ri as $file) { 
    $file->isDir() ? rmdir($file) : unlink($file); 
} 
+1

WOW,這麼多更簡單...謝謝!在php.net上做了一些閱讀,希望我在RecursiveDirectoryIterator之前瞭解它。 – Terry

+0

@Terry學習是一個繼續的事情...很高興我能夠幫助 – Baba