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
Susan SarandonOriginal
2024-12-17 21:24:11332browse

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);
  }
}

Example Usage

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

rrmdir('path/to/directory');

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!

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