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: delete directories with php, delete files in php, directory delete with php, file delete with php, glob(), php code to delete files, php delete, php glob, php unlink, recurssive file delete in php, recurssive file search in php, unlink

Thanks guys, I just about lost it looking for this.
Awesome!
Script is too good.
Thank you all. Glad to know it was useful for all.