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
PHP Delete Directory that is not empty
提问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 rmdir
page:
从 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 的文档