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

How to Delete a Directory and its Contents in PHP?

Linda Hamilton
Release: 2024-12-25 22:37:16
Original
1015 people have browsed it

How to Delete a Directory and its Contents in PHP?

Deleting a Directory with Nested Files

Q: I'm trying to delete a directory using rmdir() but it fails if the directory contains files. How can I delete a directory and all of its contents?

A: Here are two methods to delete a directory with all its files:

  1. Recursive Deletion: Recursively iterate through the directory and delete each file and subdirectory before removing the parent directory.
function deleteDir(string $dirPath): void {
    if (! is_dir($dirPath)) {
        throw new InvalidArgumentException("$dirPath must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            deleteDir($file);
        } else {
            unlink($file);
        }
    }
    rmdir($dirPath);
}
Copy after login
  1. RecursiveIterator Iteration: For PHP 5.2 and above, use RecursiveIterator() to iterate over the directory and its contents.
function removeDir(string $dir): void {
    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($it,
                 RecursiveIteratorIterator::CHILD_FIRST);
    foreach($files as $file) {
        if ($file->isDir()){
            rmdir($file->getPathname());
        } else {
            unlink($file->getPathname());
        }
    }
    rmdir($dir);
}
Copy after login

Either of these methods will effectively delete a directory including all its files and subdirectories.

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

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