Remove Contents and Delete The Directory in PHP

With the below PHP code you can recursively delete all the contents in the directory and then the directory itself.  This function checks for sub files and sub directories and delete them first before deleting the main folder.


$directory      = "uploads";

if(is_dir($directory)){
recursiveRemoveDirectory($directory);
}

function recursiveRemoveDirectory($directory) {
foreach(glob("{$directory}/*") as $file) {
if(is_dir($file)) {
recursiveRemoveDirectory($file);
} else {
unlink($file);
}
}
rmdir($directory);
}

Hope this helps. Thank You.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s