php - 如何使用 PHP 删除包含内容的文件夹

标签 php file filesystems directory

我需要使用 PHP 删除包含内容的文件夹。 rmdir()unlink() 删除空文件夹,但不能删除有内容的文件夹。

最佳答案

此功能将允许您删除任何文件夹(只要它是可写的)及其文件和子目录。

function Delete($path)
{
    if (is_dir($path) === true)
    {
        $files = array_diff(scandir($path), array('.', '..'));

        foreach ($files as $file)
        {
            Delete(realpath($path) . '/' . $file);
        }

        return rmdir($path);
    }

    else if (is_file($path) === true)
    {
        return unlink($path);
    }

    return false;
}

或者不使用 RecursiveDirectoryIterator 进行递归:

function Delete($path)
{
    if (is_dir($path) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);

        foreach ($files as $file)
        {
            if (in_array($file->getBasename(), array('.', '..')) !== true)
            {
                if ($file->isDir() === true)
                {
                    rmdir($file->getPathName());
                }

                else if (($file->isFile() === true) || ($file->isLink() === true))
                {
                    unlink($file->getPathname());
                }
            }
        }

        return rmdir($path);
    }

    else if ((is_file($path) === true) || (is_link($path) === true))
    {
        return unlink($path);
    }

    return false;
}

关于php - 如何使用 PHP 删除包含内容的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1334398/

相关文章:

php - Symfony 5 - 同一页面上的多个表单

php - Laravel 路由 : page you are looking for could not be found

php - windows wamp服务器上的ffmpeg命令

c++ - 如何从 main.cpp 文件中的单独 cpp 文件调用函数?

Windows 2008 : Virtual file system(like FUSE)

javascript - 简单的 JS 刷新 Div 不工作

android - 如何在Android中将音频文件发布到服务器

c++ - ifstream tellg() 没有返回正确的位置

linux - ext4 为目录条目启用哈希

java - Java如何获取目录的最新文件