Recipe 24.11. Removing a Directory and Its Contents

24.11.1. Problem

You want to remove a directory and all of its contents, including subdirectories and their contents.

24.11.2. Solution

Use RecursiveDirectoryIterator and RecursiveIteratorIterator, specifying that children (files and subdirectories) should be listed before their parents, as in Example 24-26.

Obliterating a directory

<?php function obliterate_directory($dir) {     $iter = new RecursiveDirectoryIterator($dir);     foreach (new RecursiveIteratorIterator($iter, RecursiveIteratorIterator::CHILD_FIRST)    as $f) {         if ($f->isDir()) {             rmdir($f->getPathname());         } else {             unlink($f->getPathname());         }     }     rmdir($dir); } obliterate_directory('/tmp/junk'); ?>

24.11.3. Discussion

Removing files, obviously, can be dangerous. Because PHP's built-in directory removal function, rmdir( ), works only on empty directories, and unlink( ) can't accept shell wildcards, the RecursiveIteratorIterator must be told to provide children before parents with its CHILD_FIRST constant.

However, that constant is not available before PHP 5.1. If you're using an earlier version of PHP, you can use the function in Example 24-27 for the same purpose.

Obliterating a directory without RecursiveIteratorIterator

<?php function obliterate_directory($dir) {     foreach (new DirectoryIterator($dir) as $file) {         if ($file->isDir()) {             if (! $file->isDot()) {                 obliterate_directory($file->getPathname());             }         } else {             unlink($file->getPathname());         }     }     rmdir($dir); } ?>

24.11.4. See Also

Documentation on rmdir( ) at and on RecursiveIteratorIterator at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: