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

How to Recursively Delete a Directory and Its Contents in PHP?

Susan Sarandon
Release: 2024-12-17 21:24:11
Original
277 people have browsed it

How to Recursively Delete a Directory and Its Contents in PHP?

Deleting a Directory and Its Contents with PHP Recursively

Problem

Need a method to eliminate a directory along with all its files and nested directories in PHP.

Solution

PHP provides a comprehensive solution for this task, allowing you to delete a directory and all its contents recursively. Here's a user-contributed implementation from the rmdir manual page:

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

Example Usage

To use this function, simply provide the path to the directory you want to delete:

rrmdir('path/to/directory');
Copy after login

The above is the detailed content of How to Recursively Delete a Directory and Its 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