Home > Backend Development > PHP Tutorial > PHP删除目录及其下的全部文件的代码

PHP删除目录及其下的全部文件的代码

WBOY
Release: 2016-06-13 11:19:29
Original
772 people have browsed it

PHP删除目录及其下的所有文件的代码
代码1:

<?php //循环删除目录和文件函数      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<br />\n";         }         }         }         closedir( $handle );         if( rmdir( $dirName ) )echo "成功删除目录: $dirName<br>\n";      }      }      ?>  
Copy after login


函数代码二:仅删除指定目录下的文件,不删除目录文件夹。
class shanchu {      //循环目录下的所有文件      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<br>\n";         }         }         }         closedir( $handle );      }      }      }      ?>      <?php $user = new shanchu();      $user->delFileUnderDir();            ?>
Copy after login

使用方法示例:

假设需要删除一个名叫"upload"的同级目录即此目录下的所有文件,你可以通过以下代码完成:
    <?php delDirAndFile( 'upload');      ?>  
Copy after login

假设需要删除一个名叫"upload"目录下的所有文件(但无需删除目录文件夹),通过以下代码完成:
<?php delFileUnderDir( 'upload');  ?>  
Copy after login
    
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