To delete a directory and its contents in PHP, you can use the rmdir()
function along with the glob()
function. Here's an example:
function deleteDirectory($path) {
if (!is_dir($path)) {
return;
}
$files = glob($path . '/*');
foreach ($files as $file) {
if (is_dir($file)) {
deleteDirectory($file);
} else {
unlink($file);
}
}
rmdir($path);
}
In the above code, the deleteDirectory()
function recursively loops through all files and directories inside the specified directory. If a file is encountered, unlink()
function is used to delete it. If a directory is encountered, the function calls itself again to delete the directory and its contents.
Finally, rmdir()
function is used to delete the empty directory itself.
To use this function, you can simply call it with the directory path as a parameter:
deleteDirectory('/path/to/directory');
Make sure to replace /path/to/directory
with the actual directory path that you want to delete.