You want to remove a directory and all of its contents, including subdirectories and their contents.
Use RecursiveDirectoryIterator and RecursiveIteratorIterator, specifying that children (files and subdirectories) should be listed before their parents:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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'); |
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 befor parents with its CHILD_FIRST constant.