Saturday, March 13, 2010

12:02 AM

PHP has the rmdir( ) function that takes a directory name as its only parameter and will remove the specified directory from the file system, if the process running your script has the right to do so. However, the rmdir() function works only on empty directories. The example below deletes empty directory named "temporary":

<?php
 rmdir( "temporary" );
?>
If you want to delete non-empty directory, you should use the recursion. In the following example we create recursive function named deleteDir() that takes a directory name as a parameter and will go through each subdirectory, deleting files as they go. When the directory is empty, we use rmdir() to remove it.
<?php
function deleteDir($dir) {
   // open the directory
   $dhandle = opendir($dir);

   if ($dhandle) {
      // loop through it
      while (false !== ($fname = readdir($dhandle))) {
         // if the element is a directory, and 
         // does not start with a '.' or '..'
         // we call deleteDir function recursively 
         // passing this element as a parameter
         if (is_dir( "{$dir}/{$fname}" )) {
            if (($fname != '.') && ($fname != '..')) {
               echo "<u>Deleting Files in the Directory</u>: {$dir}/{$fname} <br />";
               deleteDir("$dir/$fname");
            }
         // the element is a file, so we delete it
         } else {
            echo "Deleting File: {$dir}/{$fname} <br />";
            unlink("{$dir}/{$fname}");
         }
      }
      closedir($dhandle);
    }
   // now directory is empty, so we can use
   // the rmdir() function to delete it
   echo "<u>Deleting Directory</u>: {$dir} <br />";
   rmdir($dir);
}

// call deleteDir function and pass to it 
// as a parameter a directory name
deleteDir("temporary");
?>
Another way to delete non-empty directory is to use RecursiveDirectoryIterator and RecursiveIteratorIterator. The RecursiveIteratorIterator must be told to provide children (files and subdirectories) before parents with its CHILD_FIRST constant. Have a look at the code:
<?php
function deleteDir($dir) {
   $iterator = new RecursiveDirectoryIterator($dir);
   foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) 
   {
      if ($file->isDir()) {
         rmdir($file->getPathname());
      } else {
         unlink($file->getPathname());
      }
   }
   rmdir($dir);
}

deleteDir("temporary");
?>
Note: The CHILD_FIRST constant was added with PHP 5.1

0 comments: