PHP Remove or Delete Directory Recursively

Recursively delete all files and folders from a given path and can be used anywhere you wish to delete directory recursively.

By Tim Trott | PHP Tutorials | July 28, 2010

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

Care should be taken when deleting recursively as it can be easy to accidentally delete files with no way to recover them.

Delete Directory Recursively

php
/**
 * 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);
  }
}
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

We respect your privacy, and will not make your email public. Learn how your comment data is processed.