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

PHPServer Side ProgrammingProgramming

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);
raja
Published on 07-Apr-2020 14:54:11
Advertisements