At many times we need to empty a directory. Of course PHP has the filesystem functions like unlink() and rmdir() to delete files and directories. At first we may think that simply usermdir() will solve the problem. Unfortunately it’s not. rmdir() only removes empty directory. If the directory is not empty, it will return false.
In order to remove a directory and its contents, we have to remove its contents first, consisting of files and subdirectories. To make things more complicated, the subdirectories also contains files and another subdirectories in it.
It seems like this is a difficult task to solve. But in contrast, this is a very simple recursive function. See the code below.
<?php
/**
* This function removes a directory and its contents.
* Use with careful, no undo!
*/
function rmdir_recursive($dir)
{
$files = scandir($dir);
foreach ($files as $file) {
if ($file == '.' OR $file == '..') continue;
$file = "$dir/$file";
if (is_dir($file)) {
rmdir_recursive($file);
rmdir($file);
} else {
unlink($file);
}
}
rmdir($dir);
}
The function determines if argument is a regular file or a directory. If it is a regular file, it will remove the file. If it is a directory, it will remove its contents first by calling the function itself, and then removes the empty directory.
Note that the function above removes a directory. If what you need is remove directory contents, simply comment out this code:
rmdir($dir)