Skip to content

How do I recursively delete a directory and its entire contents (files + sub

In PHP, you can use the rmdir() function to remove a directory, and the unlink() function to remove a file. To recursively delete a directory and its entire contents, you can use a combination of these two functions along with the scandir() function to scan the contents of the directory. Here's some sample code that demonstrates how this can be done:

Example of recursively deleting a directory and its entire contents in PHP

php
<?php

function delete_directory($dir)
{
  if (!file_exists($dir)) {
    return true;
  }

  if (!is_dir($dir)) {
    return unlink($dir);
  }

  foreach (scandir($dir) as $item) {
    if ($item == '.' || $item == '..') {
      continue;
    }

    if (!delete_directory($dir . DIRECTORY_SEPARATOR . $item)) {
      return false;
    }
  }

  return rmdir($dir);
}

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

You can then call this function with the path of the directory you want to delete as an argument, and it will recursively delete the directory and all of its contents.

Example of deleting a directory and all of its contents recursively in PHP

php
delete_directory("/path/to/directory");

Note: Be Careful with this function as it can cause data loss if used on the wrong directory, it's highly recommended to test it on a safe environment before using it on production.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.