Delete/Remove Directory and All Subdirectories Recursively

The Problem In some occasions we need to remove files from the disk. For this purpose we use the unlink function. If we need to remove a directory, we use the rmdir function. Both functions require that we specify the name of the file or directory we wish to be removed. In addition the rmdir function requires that the directory is empty. What if we would like to remove a directory no matter what files and subdirectories it contains?

Solution

We will create a function to remove a directory and all its contents. The function will need to remove all the directory contents before calling the rmdir function. This can be achieved by:

  • calling the unlink function for each file
  • invoking the same function recursively for each subdirectory
  • the special names must not be processed '.' and '..'

We want the process to be aborted if something wrong happens. The calling environment must receive the status of the operation.

A good practise is to implement helper functins as static class members. We can group functions for directory management in a Helper_Directory class.

 
/**
 * Directory helper routines.
 *
 * @author Ivan Georgiev
 */
class Helper_Directory {
	/**
	 * Remove a directory and all its content - files and subdirectories.
	 *
	 * @param string $rootDirectory
	 * @return boolean Retruns TRUE if the operation completed successfully.
	 */
	function removeRecursively($rootDirectory) {
		if ( ! is_dir($rootDirectory) ) return false;
		$oDir = dir($rootDirectory);
		$result = true;
		while ( false !== ($entry = $oDir->read()) ) {
			if ( $entry == '.' ) continue;
			if ( $entry == '..' ) continue;
			$entryPath = $rootDirectory . DIRECTORY_SEPARATOR . $entry;
			if ( is_dir($entryPath) ) {
				if ( ! Helper_Directory ::removeRecursively($entryPath) ) {
					$result = false;
					break;
				}
			} elseif ( is_file($entryPath) ) {
				if ( ! unlink($entryPath) ) {
					$result = false;
					break;
				}
			}
		}
		$oDir->close();
 
		if ( $result ) {
			$result = rmdir($rootDirectory);
		}
		return $result;
	}
}

Discussion

We scan the directory content using the PHP's directory object returned by the dir() function. The function behaves like a iterator over the directory content. For each item we check if this is a system item (with name '.' or '..'). If it is a file than we remove it using the unlink function. For directories we call the removeRecursively() method recursively to remove the sub directory. For each delete operation we check the status and if it failed, we interrupt the process.

To find the type of items, we use the is_file() and is_dir() functions.

The following example shows how we can remove the E:/tmp directory.

// Define the directory for removal.
$dirToRemove = "E:/tmp";
if (Helper_Directory::removeRecursively($dirToRemove)) {
	// The method returned TRUE, i.e. operation successful.
	print "Directory '$dirToRemove' remove successful.";
} else {
	// The method returned FALSE, i.e. operation failed.
	print "Failed to remove '$dirToRemove'";
}

custom assignment resume writing services

 
php/recursivedirectorydelete.txt · Last modified: 2012/01/31 12:51 by piternoize
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki