Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Delete Directory that is not empty [duplicate]

Tags:

directory

php

Possible Duplicate:
how to delete a folder with contents using PHP

I know that you can remove a folder that is empty with rmdir. And I know you can clear a folder with the following three lines.

foreach($directory_path as $file) {
       unlink($file);
}

But what if one of the files is actually a sub directory. How would one get rid of that but in an infinite amount like the dual mirror effect. Is there any force delete directory in php?

Thanks

like image 223
Jjack Avatar asked Sep 02 '11 18:09

Jjack


1 Answers

This function will delete a directory recursively:

function rmdir_recursive($dir) {
    foreach(scandir($dir) as $file) {
        if ('.' === $file || '..' === $file) continue;
        if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
        else unlink("$dir/$file");
    }
    rmdir($dir);
}

This one too:

function rmdir_recursive($dir) {
    $it = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
    $it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
    foreach($it as $file) {
        if ($file->isDir()) rmdir($file->getPathname());
        else unlink($file->getPathname());
    }
    rmdir($dir);
}
like image 54
Arnaud Le Blanc Avatar answered Sep 18 '22 13:09

Arnaud Le Blanc