Home >Backend Development >PHP Tutorial >How Can I Recursively Delete a Directory and Its Contents in PHP?

How Can I Recursively Delete a Directory and Its Contents in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 00:01:10853browse

How Can I Recursively Delete a Directory and Its Contents in PHP?

Directory Deletion with Recursive Traversal in PHP

Problem:

How can we effectively delete a directory and its entire contents, including any subdirectories and associated files, using PHP?

Answer:

To tackle this recursive directory deletion task, we utilize a user-contributed method from the rmdir manual page:

function rrmdir($dir) {
    // Verify if the specified path is a valid directory
    if (is_dir($dir)) {
        // Retrieve a list of files and subdirectories within the directory
        $objects = scandir($dir);

        // Iterate through each item in the directory
        foreach ($objects as $object) {
            // Exclude hidden files and directories (dot files)
            if ($object !== "." && $object !== "..") {
                // If the item is a directory, recursively delete it
                if (is_dir($dir . DIRECTORY_SEPARATOR . $object) && !is_link($dir . "/" . $object)) {
                    rrmdir($dir . DIRECTORY_SEPARATOR . $object);
                } else {
                    // Delete the item if it's a file
                    unlink($dir . DIRECTORY_SEPARATOR . $object);
                }
            }
        }

        // Once all items within the directory have been removed, remove the directory itself
        rmdir($dir);
    }
}

The above is the detailed content of How Can I Recursively Delete a Directory and Its Contents in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn