Web Design that taps into the haromny and vision of your dreams.

PHP Remove or Delete Directory Recursively

By on in Coding

106 words, estimated reading time 1 minutes.

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);
}
}

Last updated on: Sunday 12th August 2018

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.