Home  >  Article  >  php教程  >  php中rmdir删除非空目录程序代码

php中rmdir删除非空目录程序代码

WBOY
WBOYOriginal
2016-06-08 17:24:171235browse

在php中rmdir是不能直接删除非空目录的,如果想利用rmdir来删除非空目录我们需要遍历目录然后来删除目录中的文件再删除目录的文件夹即可实现,

rmdir() 函数删除空的目录。

 代码如下 复制代码

$path = "images";
if(!rmdir($path))
  {
  echo ("Could not remove $path");
  }
else
{
 echo '删除目录失败,因为images非空目录';
}
?>

如果images是空目录可成功删除,如果非空目录就删除不了


代码如下

 代码如下 复制代码

// 说明: 删除非空目录的解决方案

function removeDir($dirName)
{
    if(! is_dir($dirName))
    {
        return false;
    }
    $handle = @opendir($dirName);
    while(($file = @readdir($handle)) !== false)
    {
        if($file != '.' && $file != '..')
        {
            $dir = $dirName . '/' . $file;
            is_dir($dir) ? removeDir($dir) : @unlink($dir);
        }
    }
    closedir($handle);
     
    return rmdir($dirName) ;
}
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn