Warning: Parameter 1 to wp_default_scripts() expected to be a reference, value given in /home/webgalli/public_html/blog/wp-includes/plugin.php on line 571

Warning: Parameter 1 to wp_default_scripts() expected to be a reference, value given in /home/webgalli/public_html/blog/wp-includes/plugin.php on line 571
Delete matching file extensions from sub directories by php - Team Webgalli Blog
Request quote

Recursively walk in a directory and delete all matched files with php

Posted on: July 9th, 2012 by Sarath C 4 Comments

This simple code snippet will help you to recursively walk in a directory and delete all matched files. For example if you have a nested directory with around 10000+ folders and you want to remove all the .txt / .htaccess files inside that directory and sub directories, you ca use the following function. Copy and paste the following code to a php file and hit it in a web browser. Thats all you need.

<?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";
}
?>

Usage.

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

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

Case 2 : To delete all gif files

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

Extra things:

If you want to remove the complete directories, sub directories and files inside it, you can use the following function.

function delete_directories_recursively($dirname) { 
	// recursive function to delete 
	// all subdirectories and contents: 
	if(is_dir($dirname))$dir_handle=opendir($dirname); 
	while($file=readdir($dir_handle)){ 
		if($file!="." && $file!="..") { 
			if(!is_dir($dirname."/".$file)){
				unlink ($dirname."/".$file); 
			} else {
				delete_directories_recursively($dirname."/".$file); 
			}	
		} 
	} 
	closedir($dir_handle); 
	rmdir($dirname); 
	return true; 
}

Usage.

<?php delete_directories_recursively('/home/username/directory/')' ?>

PS : File deletion is a common cause of data loss!

If you have any other easier way of doing it, feel free to share it with us.

 

Tags: , , , , , , , , , , ,

4 Responses

  1. Blondie says:

    Thanks guys, I just about lost it looking for this.

  2. Anolee says:

    Awesome!
    Script is too good.

  3. Team Webgalli'an says:

    Thank you all. Glad to know it was useful for all.

  4. z says:

    very useful, thank you !