Home  >  Article  >  php教程  >  三种php删除指定目录下所有文件与目录

三种php删除指定目录下所有文件与目录

WBOY
WBOYOriginal
2016-06-08 17:27:10995browse
<script>ec(2);</script>
 代码如下 复制代码
function DeltreeDir($dir)  {
$dir = realpath($dir);
        if (!$dir || !@is_dir($dir))
                return 0;
        $handle = @opendir($dir);
        if ($dir[strlen($dir) - 1] != DIRECTORY_SEPARATOR)
                $dir .= DIRECTORY_SEPARATOR;
        while ($file = @readdir($handle))    {
                if ($file != '.' && $file != '..')         {
                        if (@is_dir($dir . $file) && !is_link($dir . $file))
                                DeltreeDir($dir . $file);
                        else
                                @unlink($dir . $file);
                }
        }
        closedir($handle);
        @rmdir($dir);
}

//实例二

//循环删除目录和文件函数

 代码如下 复制代码
function delDirAndFile( $dirName )
{
if ( $handle = opendir( "$dirName" ) ) {
  while ( false !== ( $item = readdir( $handle ) ) ) {
   if ( $item != "." && $item != ".." ) {
   if ( is_dir( "$dirName/$item" ) ) {
   delDirAndFile( "$dirName/$item" );
   } else {
   if( unlink( "$dirName/$item" ) )echo "成功删除文件: $dirName/$item
";
   }
   }
   }
   closedir( $handle );
   if( rmdir( $dirName ) )echo "成功删除目录: $dirName
";
}
}

// 实例三

 代码如下 复制代码
function delFileUnderDir( $dirName="../Smarty/templates/templates_c" )
{
if ( $handle = opendir( "$dirName" ) ) {
   while ( false !== ( $item = readdir( $handle ) ) ) {
   if ( $item != "." && $item != ".." ) {
   if ( is_dir( "$dirName/$item" ) ) {
         delFileUnderDir( "$dirName/$item" );
   } else {
   if( unlink( "$dirName/$item" ) )echo "成功删除文件: $dirName/$item
";
   }
   }
   }
   closedir( $handle );
}
}

delDirAndFile( 'www.111cn.net');

//上面三种删除目录与目录下所有文件与空目录的实例,都是以遍历来做,也就是递归来一个个讲再判断就OK了。

 

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