PHP: Unlink All Files Within A Directory, and then Deleting That Directory


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: 07-Apr-2020

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements