"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > PHP recursively deletes directories and their content methods

PHP recursively deletes directories and their content methods

Posted on 2025-04-14
Browse:865

How to Recursively Delete Directories and Their Contents in PHP?

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:

  1. The rrmdir() function begins by verifying if the specified $dir is a directory.
  2. It then iterates through the directory's contents using scandir.
  3. For each file or subdirectory encountered:

    • If it's a subdirectory (not "." or ".."), it checks if it's a genuine subdirectory (not a link) and recursively calls rrmdir() to delete its contents.
    • Otherwise, it directly deletes the file.
  4. Finally, once all contents have been removed, the original directory ($dir) is deleted.
Latest tutorial More>

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