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

问题描述

我正在尝试使用rmdir删除目录,但是我收到Directory not empty消息,因为它仍然有文件。

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?

推荐答案

没有内置函数来执行此操作,但请参阅底部的评论。许多评论者发布了自己的递归目录删除功能。您可以从中选择。

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
}

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

07-30 12:08