Home > Backend Development > PHP Tutorial > php递归删除目录下的文件但保留的实例分享_PHP

php递归删除目录下的文件但保留的实例分享_PHP

WBOY
Release: 2016-06-01 11:53:17
Original
935 people have browsed it

用php程序删除目录和文件比到ftp删除有很多优势。首先进ftp就比较麻烦,然后删除大量文件的时候ftp删除很慢,还有就是程序只想删除文件夹下面的文件,而保留目录结构,可以用php来轻松的实现,再有比如生成的日志、缓存要清除用程序来完成显然轻松的多。

一:删除目录下面的文件,不删除目录

复制代码 代码如下:
function delFileUnderDir( $dirName ){ 
 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
\n"; 
     } 
    } 
   } 
   closedir( $handle ); 
 } 
}

二:删除目录及目录下所有的文件

复制代码 代码如下:
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
\n"; 
      } 
    } 
   } 
   closedir( $handle ); 
   if( rmdir( $dirName ) ) echo "成功删除目录: $dirName
\n"; 
 } 
}

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template