Removing non-empty directories and subdirectories in PHP
October 24, 2009 Category :php| Web Devlopment 8
Here’s a snippet that can help you to remove a non-empty directory from the server. It’s a recursive function that deletes the directory with its files, folders and sub-folders.
function delete_directory($dir)
{
if ($handle = opendir($dir))
{
$array = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($dir.$file))
{
if(!@rmdir($dir.$file)) // Empty directory? Remove it
{
delete_directory($dir.$file.'/'); // Not empty? Delete the files inside it
}
}
else
{
@unlink($dir.$file);
}
}
}
closedir($handle);
@rmdir($dir);
}
}
$dir = '/home/path/to/mysite.com/folder_to_delete/'; // IMPORTANT: with '/' at the end
$remove_directory = delete_directory($dir);