function delete_directory( $dir ) {
// Check if $dir is a directory.
if ( ! is_dir( $dir ) ) {
return false; // No need to continue if it's not a directory.
}
// Get all files and folders in the directory.
$items = scandir( $dir );
// Loop through items in the directory.
foreach ( $items as $item ) {
// Skip special entries "." (current directory) and ".." (parent directory)
if ( $item == '.' || $item == '..' ) {
continue;
}
// Build the full path of the current item.
$path = $dir . DIRECTORY_SEPARATOR . $item;
// If the item is a directory, call this function recursively.
if ( is_dir( $path ) ) {
delete_directory( $path );
} else { // If the item is a file, delete it.
unlink( $path );
}
}
// Remove the main directory.
return rmdir( $dir );
}
Delete directory using rmdir() in PHP even if the directory is not empty
This post brought to you by RocketGeek, ButlerBlog, and the following: