欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

rrmdir php中递归删除目录及目录下的文件

程序员文章站 2022-12-26 11:31:01
复制代码 代码如下: function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); forea...
复制代码 代码如下:

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
(php 4, php 5)
rmdir — 删除目录
report a bug 说明
bool rmdir ( string $dirname )
尝试删除 dirname 所指定的目录。 该目录必须是空的,而且要有相应的权限。成功时返回 true, 或者在失败时返回 false.
note: 自 php 5.0.0 起 rmdir() 也可用于某些 url 封装协议。参见supported protocols and wrappers 的列表看看 rmdir() 支持哪些 url 封装协议。
note: 在 php 5.0.0 中增加了 对上下文(context)的支持。有关 上下文(context) 的说明参见 stream 函数。
note: 当启用 安全模式时, php 会在执行脚本时检查被脚本操作的目录是否与被执行的脚本有相同的 uid(所有者)。
参见 mkdir() 和 unlink()。
复制代码 代码如下:

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

this isn't my code, but just thought i would share, since it took me so long to find. this is a function to delete a folder, all sub-folders, and files in one clean move.
just tell it what directory you want deleted, in relation to the page that this function is executed. then set $empty = true if you want the folder just emptied, but not deleted. if you set $empty = false, or just simply leave it out, the given directory will be deleted, as well.
复制代码 代码如下:


<?php
function deleteall($directory, $empty = false) {
if(substr($directory,-1) == "/") {
$directory = substr($directory,0,-1);
}
if(!file_exists($directory) || !is_dir($directory)) {
return false;
} elseif(!is_readable($directory)) {
return false;
} else {
$directoryhandle = opendir($directory);
while ($contents = readdir($directoryhandle)) {
if($contents != '.' && $contents != '..') {
$path = $directory . "/" . $contents;
if(is_dir($path)) {
deleteall($path);
} else {
unlink($path);
}
}
}
closedir($directoryhandle);
if($empty == false) {
if(!rmdir($directory)) {
return false;
}
}
return true;
}
}
?>
[/code]
a patch to previous script to make sure rights for deletion is set:
复制代码 代码如下:

<?php
//delete folder function
function deletedirectory($dir) {
if (!file_exists($dir)) return true;
if (!is_dir($dir) || is_link($dir)) return unlink($dir);
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
if (!deletedirectory($dir . "/" . $item)) {
chmod($dir . "/" . $item, 0777);
if (!deletedirectory($dir . "/" . $item)) return false;
};
}
return rmdir($dir);
}
?>

更多说明可以参考