简体   繁体   中英

Deleting files matching a specific file extension recursivly?

I would like to delete all files matching a particular extension in a specified directory and all subtree. I suppose I should be using using unlink but some help would be highly appreciated... Thank you!

you need a combination of this

Recursive File Search (PHP)

And the unlink / delete

You should be able to edit the example instead of echoing the file, to delete it

To delete specific extension files from sub directories, you can use the following function. Example:

<?php 
function delete_recursively_($path,$match){
   static $deleted = 0,
   $dsize = 0;
   $dirs = glob($path."*");
   $files = glob($path.$match);
   foreach($files as $file){
      if(is_file($file)){
         $deleted_size += filesize($file);
         unlink($file);
         $deleted++;
      }
   }
   foreach($dirs as $dir){
      if(is_dir($dir)){
         $dir = basename($dir) . "/";
         delete_recursively_($path.$dir,$match);
      }
   }
   return "$deleted files deleted with a total size of $deleted_size bytes";
}
?>

eg To remove all text files you can use it as follows:

<?php echo delete_recursively_('/home/username/directory/', '.txt'); ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM