Recursively Deleting Directories and Their Contents in PHP
When tasked with eliminating a directory and its entire structure in PHP, a recursive approach is often sought. This involves efficiently purging not only files within the target directory but also any nested subdirectories and their contents.
Solution:
The PHP manual's user-contributed section for rmdir provides a practical implementation for this recursive deletion scenario:
function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (is_dir($dir . DIRECTORY_SEPARATOR . $object) && !is_link($dir . "/" . $object)) { rrmdir($dir . DIRECTORY_SEPARATOR . $object); } else { unlink($dir . DIRECTORY_SEPARATOR . $object); } } } rmdir($dir); } }
How it Works:
For each file or subdirectory encountered:
The above is the detailed content of How to Recursively Delete Directories and Their Contents in PHP?. For more information, please follow other related articles on the PHP Chinese website!