PHP 删除非空目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7288029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:24:09  来源:igfitidea点击:

PHP Delete Directory that is not empty

phpdirectory

提问by JHyman

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

可能的重复:
如何使用 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.

我知道您可以使用 rmdir 删除空文件夹。而且我知道您可以使用以下三行清除文件夹。

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?

但是如果其中一个文件实际上是一个子目录呢?如何摆脱它,但像双镜效应一样无穷无尽。php中是否有强制删除目录?

Thanks

谢谢

回答by Arnaud Le Blanc

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

回答by Paul DelRe

From PHP rmdirpage:

从 PHPrmdir页面:

<?php 
 function rrmdir($dir) { 
   if (is_dir($dir)) { 
     $objects = scandir($dir); 
     foreach ($objects as $object) { 
       if ($object != "." && $object != "..") { 
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); 
       } 
     } 
     reset($objects); 
     rmdir($dir); 
   } 
 } 
?>

And

<?php 
function delTree($dir) { 
    $files = glob( $dir . '*', GLOB_MARK ); 
    foreach( $files as $file ){ 
        if( substr( $file, -1 ) == '/' ) 
            delTree( $file ); 
        else 
            unlink( $file ); 
    } 

    if (is_dir($dir)) rmdir( $dir ); 

} 
?>

回答by genesis

<?php 
 function rrmdir($dir) { 
   if (is_dir($dir)) { 
     $objects = scandir($dir); 
     foreach ($objects as $object) { 
       if ($object != "." && $object != "..") { 
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); 
       } 
     } 
     reset($objects); 
     rmdir($dir); 
   } 
 } 
?>

from PHP's documentation

来自 PHP 的文档