Empty directory recursively in PHP

Sometime we need to delete all contents in the directory whether it is any files or directory. At that time this function will be handy to fulfill our need. It empties the folder recursively, that means all the folders ans sub-folders are removed. Two parameters are passed in the function, First one is the directory to be emptied and second one is the flag to determine whether to delete the given folder.
If set true, given folder is also removed at last. If emptying is not our need then you should pass false.

/**
 * Empty directory
 *
 * @param  string  $dirname     Directory
 * @param  boolean $self_delete Delete current directory or not
 * @return bool                 TRUE if success
 */
function emptyDirectory( $dirname, $self_delete = false ) {
	$dir_handle = null;
	if ( is_dir( $dirname ) ) {
		$dir_handle = opendir( $dirname );
	}
	if ( ! $dir_handle ) {
		return false;
	}
	while ( $file = readdir( $dir_handle ) ) {
		if ( $file != '.' && $file != '..' ) {
			if ( ! is_dir( $dirname . '/' . $file ) ) {
				unlink( $dirname . '/' . $file );
			} else {
				emptyDirectory( $dirname . '/' . $file, true );
			}
		}
	}
	closedir( $dir_handle );
	if ( $self_delete ) {
		@rmdir( $dirname );
	}
	return true;
}

Leave a Reply

Your email address will not be published. Required fields are marked *