Delete files and subdirectory files


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2.  * Delete files in given path (and subdirs)
  3.  *
  4.  * <code> echo deleteFiles('c:/TEMP/greeting/','3019*.vox' ); </code>
  5.  *
  6.  * @param string $path Path to the files to delete (should end with slash or backslash)
  7.  * @param string $match Filename(s) to delete (use * as wildcard)
  8.  * @param boolean $delSubdirs Delete matching files in subdirs
  9.  * @return integer Returns how many files that were deleted
  10.  */
  11. function deleteFiles($path, $match, $delSubdirFiles = false){
  12. static $deleted = 0;
  13. $dirs = glob($path."*",GLOB_NOSORT); // GLOB_NOSORT to make it quicker
  14. $files = glob($path.$match, GLOB_NOSORT);
  15.  
  16. foreach ($files as $file){
  17. if(is_file($file)){
  18. unlink($file);
  19. $deleted++;
  20. }
  21. }
  22. if ($delSubdirFiles) {
  23. foreach ($dirs as $dir){
  24. if (is_dir($dir)){
  25. $dir = basename($dir) . "/";
  26. deleteFiles($path.$dir,$match);
  27. }
  28. }
  29. }
  30. return $deleted;
  31. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.