How to Remove a (non-empty) Directory using PHP
Posted on September 28, 2008, Filled under PHP,
Bookmark it
Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.
Hello coders,
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.
<?php
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);
?>
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- September 28, 2008
- article by Gabriel C.
- 1 comment
Sponsors
Related Posts
-
PHP: Calculate the Size, Number of Files & Folders of a Directoryat September 24, 2008 with 3 comments
-
How to recursively read a directory with all its contentat September 4, 2008
-
PHP: How to remove empty values from an arrayat May 21, 2008 with 6 comments
-
Show random image(s) from a directoryat September 21, 2008 with 3 comments
-
PHP: Some Ways to Scan a Directoryat December 12, 2008 with 4 comments

One Reply to "How to Remove a (non-empty) Directory using PHP"
September 28, 2008 at 4:45 PM
You should start using scandir(). And yes, it’s PHP 5, everyone should be using it anyway.