Home > Backend Development > PHP Tutorial > How to Delete a Directory Containing Files in PHP?

How to Delete a Directory Containing Files in PHP?

Linda Hamilton
Release: 2024-12-05 19:09:12
Original
267 people have browsed it

How to Delete a Directory Containing Files in PHP?

Deleting Directories Containing Files

Removing a directory is easy, but what happens when the directory contains files? The rmdir() function fails if there are any files in the directory. To delete the directory, you must first delete all the files it contains.

There are several ways to do this. One option is to use a recursive function that deletes all files and folders in the directory, including any nested directories. Here's an example:

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

Alternatively, if you're using PHP 5.2 or later, you can use a RecursiveIterator to delete the directory without implementing the recursion yourself:

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

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