Recursively Delete Files and Folders and All Contents Using PHP

  • Home /
  • Blog Posts /
  • Recursively Delete Files and Folders and all Contents using PHP

Below is a quick and easy way to recursively delete all files and folders in a given path using PHP.

function destroy_dir($dir) {
  if (!is_dir($dir) || is_link($dir))
    return unlink($dir);

  foreach (scandir($dir) as $file) {
    if ($file == "." || $file == "..")
      continue;
    if (!destroy_dir($dir."/".$file)) {
      chmod($dir."/".$file, 0777);
      if (!destroy_dir($dir."/".$file)) return false;
    }
  }
  return rmdir($dir);
}

destroy_dir("/var/www/site/public_html/directory/");