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