PHP Directories Removing a Directory and Its Contents - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Directories Removing a Directory and Its Contents - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, July 15, 2019

PHP Directories Removing a Directory and Its Contents

PHP Directories



Removing a Directory and Its Contents

Problem

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

Solution

Use RecursiveDirectoryIterator and RecursiveIteratorIterator, specifying that children (files and subdirectories) should be listed before their parents:

       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');

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.

No comments:

Post a Comment

Post Top Ad