What is the best practice for deleting directories with files in PHP to ensure efficient and effective deletion?

When deleting directories with files in PHP, it is important to ensure that all files within the directory are properly deleted before attempting to delete the directory itself. This can be achieved by recursively deleting all files and subdirectories within the directory before deleting the directory itself. Additionally, it is important to handle any potential errors that may occur during the deletion process to ensure that the operation is completed successfully.

function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }
    }

    return rmdir($dir);
}

// Usage
$directoryToDelete = 'path/to/directory';
if (deleteDirectory($directoryToDelete)) {
    echo 'Directory deleted successfully.';
} else {
    echo 'Error deleting directory.';
}