Home  >  Article  >  Backend Development  >  Example of how to delete a directory and all files in php

Example of how to delete a directory and all files in php

WBOY
WBOYOriginal
2016-07-25 08:59:16950browse
  1. /**
  2. * Loop delete directory and file function
  3. * @delDirAndFile
  4. * @param $dirName
  5. * @edit bbs.it-home.org
  6. function delDirAndFile( $dirName )
  7. {
  8. if ( $handle = opendir( "$dirName" ) ) {
  9. while ( false !== ( $item = readdir( $handle ) ) ) {
  10. if ( $item != "." && $item != ".." ) {
  11. if ( is_dir( "$ dirName/$item" ) ) {
  12. delDirAndFile( "$dirName/$item" );
  13. } else {
  14. if( unlink( "$dirName/$item" ) ) echo "File deleted successfully: $dirName/$item
  15. n";
  16. }
  17. }
  18. }
  19. closedir( $handle );
  20. if( rmdir( $dirName ) ) echo "Directory deleted successfully: $dirName
  21. n";
  22. }
  23. }
  24. ?>
Copy code

Function 2, only deletes files in the specified directory, not the directory folder.

  1. /**
  2. * Loop all files in the directory
  3. * @func delFileUnderDir
  4. * @param $dirName
  5. * @edit bbs.it-home.org
  6. */
  7. function delFileUnderDir( $dirName )
  8. {
  9. if ( $handle = opendir( "$dirName" ) ) {
  10. while ( false !== ( $item = readdir( $handle ) ) ) {
  11. if ( $item != "." && $item != ".." ) {
  12. if ( is_dir( "$dirName/$item" ) ) {
  13. delFileUnderDir( "$dirName/$item" );
  14. } else {
  15. if( unlink( "$dirName/$item" ) ) echo "File deleted successfully: $dirName/$item
  16. n";
  17. }
  18. }
  19. }
  20. closedir ( $handle );
  21. }
  22. }
  23. ?>
Copy the code

Let’s look at the specific calling example. 1. Delete a sibling directory named "upload", that is, all files in this directory:

  1. delDirAndFile( 'upload');
  2. ?>
Copy code

2, delete all files in a directory named "upload" (but there is no need to delete the directory file folder):

  1. delFileUnderDir( 'upload');
  2. ?>
Copy code


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