How to delete non-empty directory with PHP?

2 04 2011

You can easily delete any empty directory with build-in function rmdir(), but it can’t delete any directory which contains some file within it. For that, you need to first delete the files inside the directory. The below function exactly does the same, it recursively delete any internal files/directories. Take a look at the code-

function deleteDirectory($directory)
{
	if(!$dh=opendir($directory))
	{
		return false;
	}
	
	while($file=readdir($dh))
	{
		if($file == "." || $file == "..")
		{
			continue;
		}
		
		if(is_dir($directory."/".$file))
		{
			deleteDirectory($directory."/".$file);
		}
		
		if(is_file($directory."/".$file))
		{
			unlink($directory."/".$file);
		}
	}
	
	closedir($dh);
	
	rmdir($directory);
}
Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: