How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?
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:
<?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);
}
Watch a video course
Learn object oriented PHP
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.
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.