7.9 Recursively Deleting a Directory


You want to remove a directory and its contents.

Technique

Use 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; } ?> 

Comments

The 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); } ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net