Dec 24 2011

Simple Function to Delete Files Matching a Pattern in Directory and sub-dir

Category: PHP,Programmingksg91 @ 2:31 pm

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.


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

Let me know if there is any improvement I can do on this code. :)

Leave a Reply