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

How Can I Recursively Delete Directories and Their Contents in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 20:31:10623browse

How Can I Recursively Delete Directories and Their Contents in PHP?

Deleting Directories with their Contents

When attempting to remove a directory using rmdir(), encountering an error due to existing files within is a common issue. Fortunately, there are several methods to circumvent this limitation:

Method 1: Recursive Deletion

Before deleting the target folder, remove all its files and subfolders recursively. Here's a sample implementation:

function deleteDir(string $dirPath): void {
    if (!is_dir($dirPath)) {
        throw new InvalidArgumentException("'$dirPath' must be a directory");
    }
    $dirPath .= '/';
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            deleteDir($file);
        } else {
            unlink($file);
        }
    }
    rmdir($dirPath);
}

Method 2: RecursiveIterator (PHP 5.2 )

Leveraging a RecursiveIterator, you can simplify the recursive deletion process:

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

By employing these methods, you can effectively delete directories along with their embedded files.

The above is the detailed content of How Can I Recursively Delete Directories and Their 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