gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:14:36 25 4
gpt4 key购买 nike

我需要使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com