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!

Get our RSS Feed!

Sponsors

Related Posts

One Reply to "How to Remove a (non-empty) Directory using PHP"

  1. You should start using scandir(). And yes, it’s PHP 5, everyone should be using it anyway.

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


  

CommentLuv Enabled