Today, a guy was asking for a small PHP function to delete all files which match a pattern in a particular directory and all it’s sub-direcory . So I wrote following simple function which uses stack to keep track of unvisited directory. It is similar to Depth-First-Search approach for traversing nodes in a tree.
[sourcecode language=”php”]
<?php
function removeFiles($dir,$pattern)
{
$stack=array();
array_push($stack,$dir);
while(true){
$dir=array_pop($stack);
if($dir==NULL)
break;
$a= glob($dir.’/’.$pattern);
foreach($a as $file) {
if(is_dir($file)) {
array_push($stack,$file);
continue;
}
unlink($file);
echo "File: ".$file." has been removed.
";
}
}
}
?>
[/sourcecode]
Let me know if there is any improvement I can do on this code. 🙂