如何删除非空目录? [英] How do I remove a directory that is not empty?

查看:32
本文介绍了如何删除非空目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 rmdir 删除一个目录,但我收到了目录非空"消息,因为其中仍有文件.

I am trying to remove a directory with rmdir, but I received the 'Directory not empty' message, because it still has files in it.

我可以使用什么函数来删除包含所有文件的目录?

What function can I use to remove a directory with all the files in it as well?

推荐答案

没有内置函数可以做到这一点,但请参阅 http://us3.php.net/rmdir.许多评论者发布了他们自己的递归目录删除功能.您可以从中挑选.

There is no built-in function to do this, but see the comments at the bottom of http://us3.php.net/rmdir. A number of commenters posted their own recursive directory deletion functions. You can take your pick from those.

这是一个看起来不错的:

function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }

    }

    return rmdir($dir);
}

如果您想保持简单,您可以只调用 rm -rf.这确实使您的脚本仅适用于 UNIX,因此请注意这一点.如果你走那条路,我会尝试这样的事情:

You could just invoke rm -rf if you want to keep things simple. That does make your script UNIX-only, so beware of that. If you go that route I would try something like:

function deleteDirectory($dir) {
    system('rm -rf -- ' . escapeshellarg($dir), $retval);
    return $retval == 0; // UNIX commands return zero on success
}

这篇关于如何删除非空目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆