PHP - Deleting Directory Contents & SubDirectory Contents I've set up some PHP to delete a directory, it's contents, and any subdirectory and its contents... I'm new to PHP so I'm most definitely doing something WRONG or am doing something in the most inefficient way.

Looking for some references or suggestion on how to do this better...

Using PHP 5.3.8.

First Draft

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

            //check if any folders exist, then delete files within
            if (file_exists($absolute_path) &amp;&amp; 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 != "." &amp;&amp; $child_entry != "..") {              
                            unlink($child_absolute_path);
                        }
                    }
                    closedir($child_handle);
                }
            }
            rmdir($absolute_path);
        }
    }
    closedir($handle);
}
rmdir($main_dir);


how about something like this...

Second Draft

 $dir = "path/to/dir";
 chmod($dir, 0755);
 $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
 $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
 foreach ( $ri as $file ) {
     $file-&gt;isDir() ?  rmdir($file) : unlink($file);
 }
 rmdir($dir);


Any thoughts? Much appreciated!
function empty_dir($dir) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),
                                              RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($iterator as $path) {
      if ($path-&gt;isDir()) {
         rmdir($path-&gt;__toString());
      } else {
         unlink($path-&gt;__toString());
      }
    }
    rmdir($dir);
}


from: http://php.net/manual/en/class.recursivedirectoryiterator.php