Unlink All Files and Delete Directory in PHP



Use glob to find all files matching a pattern.

function recursive_directory_removal($directory) {
   foreach(glob("{$directory}/*") as $file) {
      if(is_dir($file)) {
         recursive_directory_removal($file);
      } else {
         unlink($file);
      }
   }
   rmdir($directory);
}

On PHP version 5.3 and above, the following code can be used −

$dir = ...
array_walk(glob($dir . '/*'), function ($fn) {
   if (is_file($fn))
   unlink($fn);
});
unlink($dir);
Updated on: 2020-04-07T11:24:32+05:30

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements