Recursively Delete Files and Folders and all Contents using PHP

0 min read 58 words

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/");
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags