PHP:删除文件夹(包括其内容)的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1296681/
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: Simplest way to delete a folder (including its contents)
提问by Chris B
The rmdir()function fails if the folder contains any files. I can loop through all of the the files in the directory with something like this:
rmdir()如果文件夹包含任何文件,该函数将失败。我可以使用以下内容遍历目录中的所有文件:
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
unlink($dir.DIRECTORY_SEPARATOR.$item);
}
rmdir($dir);
Is there any way to just delete it all at once?
有没有办法一次性全部删除?
回答by Yuriy
rrmdir()-- recursively delete directories:
rrmdir()-- 递归删除目录:
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) rrmdir($file); else unlink($file);
} rmdir($dir);
}
回答by chaos
Well, there's always
嗯,总有
system('/bin/rm -rf ' . escapeshellarg($dir));
where available.
在可用的情况下。
回答by Gaurang P
function delete_files($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")
delete_files($dir."/".$object);
else unlink ($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
回答by Kevin Boyd
As per thissource;
根据这个来源;
Save some time, if you want to clean a directory or delete it and you're on windows.
节省一些时间,如果你想清理一个目录或删除它并且你在 Windows 上。
Use This:
用这个:
chdir ($file_system_path);
exec ("del *.* /s /q");
You can use other DEL syntax, or any other shell util. You may have to allow the service to interact with the desktop, as that's my current setting and I'm not changing it to test this.
您可以使用其他 DEL 语法或任何其他 shell 实用程序。您可能必须允许服务与桌面交互,因为这是我当前的设置,我不会更改它来测试它。
Else you could find an alternative method here.
回答by Ravinder Singh
Try this :
尝试这个 :
exec('rm -rf '.$user_dir);
回答by vinsa
This fuction delete the directory and all subdirectories and files:
此功能删除目录和所有子目录和文件:
function DelDir($target) {
if(is_dir($target)) {
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
DelDir( $file );
}
rmdir( $target );
} elseif(is_file($target)) {
unlink( $target );
}
}
回答by AMIB
One safe and good function located in php comments by lprent It prevents accidentally deleting contents of symbolic links directories located in current directory
lprent 位于 php 注释中的一个安全且良好的功能 它可以防止意外删除位于当前目录中的符号链接目录的内容
public static function delTree($dir) {
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file") && !is_link($dir)) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}

