Return to Snippet

Revision: 11678
at February 13, 2009 12:19 by fackz


Initial Code
1. <?php  
   2. function delete_directory($dir)  
   3. {  
   4. if ($handle = opendir($dir))  
   5. {  
   6. $array = array();  
   7.   
   8.     while (false !== ($file = readdir($handle))) {  
   9.         if ($file != "." && $file != "..") {  
  10.   
  11.             if(is_dir($dir.$file))  
  12.             {  
  13.                 if(!@rmdir($dir.$file)) // Empty directory? Remove it  
  14.                 {  
  15.                 delete_directory($dir.$file.'/'); // Not empty? Delete the files inside it  
  16.                 }  
  17.             }  
  18.             else  
  19.             {  
  20.                @unlink($dir.$file);  
  21.             }  
  22.         }  
  23.     }  
  24.     closedir($handle);  
  25.   
  26.     @rmdir($dir);  
  27. }  
  28.   
  29. }  
  30.   
  31. $dir = '/home/path/to/mysite.com/folder_to_delete/'; // IMPORTANT: with '/' at the end  
  32.   
  33. $remove_directory = delete_directory($dir);  
  34. ?>

Initial URL

                                

Initial Description
Here’s a snippet that can help you to remove a non-empty directory from the server. It’s a recursive function that deletes the directory with its files, folders and sub-folders.

Initial Title
How to remove a (non-empty) directory

Initial Tags
directory

Initial Language
PHP