Learning never exhausts the mind

Last Updated by

This short PHP snippet will recursively delete all files and folders from a given path and can be used anywhere you wish to delete directory recursively.

It is often a requirement for a PHP script to delete files recursively, either as a cleanup operation for cached files or to remove unwanted files. This function will allow your PHP script to delete directory and files recursively. Simply call the function passing in the path of the directory to recursively delete.

Delete Directory Recursively

/**
 * Delete a file or recursively delete a directory
 *
 * @param string $str Path to file or directory
*/

function recursiveDelete($str){
	if(is_file($str)){
		return @unlink($str);
	}
	elseif(is_dir($str)){
		$scan = glob(rtrim($str,'/').'/*');
		foreach($scan as $index=>$path){
			recursiveDelete($path);
		}
		return @rmdir($str);
	}
}

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.