TechniqueUse the maptree method from PEAR in the File_Find class (File/Find.php). <?php include_once 'File/Find.php'; $fsearcher = new File_Find; list ($subdirs, $files) = $fsearcher->maptree ($your_directory); usort($subdirectories, 'sort_len'); foreach ($files as $file) { unlink ($file) or die ("Cannot remove $file"); } foreach ($subdirectories as $directory) { rmdir ($directory) or die ("Cannot remove $directory"); } function sort_len ($a, $b) { if (strlen ($a) == strlen ($b)) { return 0; } return (strlen ($a) > strlen ($b)) ? 1 : -1; } ?> CommentsThe maptree() function in File_Find is useful not only in situations such as the following, but it is also the crux of most of the other methods (such as search ) in File_Find . Therefore, we are including the source to maptree() and all relevant methods that it implements as a further illustration of directory and file access functions. <?php var $_dirs; var $files = array(); var $directories = array(); function &maptree ($directory) { $this->_dirs = array ($directory); while (count ($this->_dirs)) { $dir = array_pop ($this->_dirs); File_Find::_build ($dir); array_push ($this->directories, $dir); } return array ($this->directories, $this->files); } // This is the File_Find::_build that was called above function _build ($directory) { $dh = @opendir ($directory); if (!$dh) { $pe = new FileFindException ("Cannot open directory"); return ($pe); } while ($entry = @readdir ($dh)) { if ($entry != '.' && $entry != '..') { $entry = "$directory/$entry"; if (is_dir ($entry)) array_push ($this->_dirs, $entry); else array_push ($this->files, $entry); } } @closedir ($dh); } ?> |