Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Delete folder recursively with PHP

Wednesday, February 20th, 2013 by Servage

Have you ever tried to manage files and folders from PHP? In some cases it makes good sense to manage some files with PHP. Say you generate images, PDF files or downloadable archives from your scripts. You may want to store dem in a file structure, instead of creating them again and again on every request.

Sometimes you also need to delete files, sometimes even large groups of files or directories including all their subdirectories. The default functionality in PHP and Unix is very careful when it comes to deleting stuff recursively. Below is a function which enables you do do that, but with the security feature of adding a root directory, from which everything must origin – tu avoid unpleasant dataloss.

function removeDir($dir, $root) {

	if (strlen($root) < 2 || $root != substr($dir, 0, strlen($root)))
		return false;
	if (file_exists($dir)) {
		if (is_dir($dir)) {
			$files = scandir($dir);
			foreach($files as $file) {
				if ($file != '.' && $file != '..') {
					$file = $dir.$file;
					if (is_dir($file)) {
						if (!removeDir($file, $root))
							return false;
					else {
						if (!unlink($file))
							return false;
			return rmdir($dir);	
			return unlink($file);
		return true;

You can simply invoke this function by writing:

removeDir('/my/path/to/dir', '/my/path');

The first argument is the dir to delete. The second is a root dir, which any deleted directory must be within.

Delete folder recursively with PHP, 3.3 out of 5 based on 3 ratings
Categories: Guides & Tutorials


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.