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:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3