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 TrottPHP Tutorials • July 28, 2010
PHP Remove or Delete Directory Recursively

It is often a requirement for a PHP script to delete files recursively or delete directory 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);
  }
}

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. 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?

New comments for this post are currently closed.