Many times in PHP, we need to delete the folder containing subfolders and files. So we have to check for depth and according to that we have to delete files first and then folders. But if we don’t know the content of it then it will be very difficult task to delete it. I am working on some stuff that need to be delete once it is utilized so I make the function that check for the subfolders and files and recursively delete the contents of it.
Here is the function for delete.
function delFolder($folder)
{
foreach(glob($folder . '/*') as $file)
{
if(is_dir($file))
delFolder($file);
else
unlink($file);
}
rmdir($folder);
}
Here delFolder is the function that perform delete task.
Here we use following of the PHP function.
- glob — Find pathnames matching a pattern
- is_dir — Tells whether the filename is a directory
- unlink — Deletes a file
- rmdir — Removes directory
Download the full example with comments here : https://www.mediafire.com/view/winyqdt2fr1jsll/delFolder.php