How can one effectively delete directories containing hidden files using PHP without encountering errors?

When deleting directories containing hidden files using PHP, errors can occur if the hidden files are not properly handled or if permissions are not set correctly. To effectively delete directories with hidden files, you can recursively iterate through the directory, check for hidden files, and delete them before deleting the directory itself.

function deleteDirectory($dir) {
    if (!is_dir($dir)) {
        return false;
    }

    $files = array_diff(scandir($dir), array('.', '..'));
    foreach ($files as $file) {
        $path = $dir . '/' . $file;
        if (is_dir($path)) {
            deleteDirectory($path);
        } else {
            if (substr($file, 0, 1) === '.') {
                unlink($path);
            }
        }
    }

    return rmdir($dir);
}

// Usage
$directory = 'path/to/directory';
deleteDirectory($directory);