Home > Backend Development > PHP Tutorial > How to Recursively Delete Directories and Their Contents in PHP?

How to Recursively Delete Directories and Their Contents in PHP?

Patricia Arquette
Release: 2024-12-08 03:58:08
Original
582 people have browsed it

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);
    }
}
Copy after login

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.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template