What are the potential pitfalls when using ftp functions to delete directories with files in PHP?

When using FTP functions to delete directories with files in PHP, a potential pitfall is that the directory may not be empty, causing the deletion to fail. To solve this issue, you can recursively delete all files within the directory before attempting to delete the directory itself.

function deleteDirectory($ftp_conn, $dir) {
    $files = ftp_nlist($ftp_conn, $dir);
    
    foreach ($files as $file) {
        if (is_dir($file)) {
            deleteDirectory($ftp_conn, $file);
        } else {
            ftp_delete($ftp_conn, $file);
        }
    }
    
    ftp_rmdir($ftp_conn, $dir);
}

// Usage example
$ftp_conn = ftp_connect('ftp.example.com');
ftp_login($ftp_conn, 'username', 'password');

deleteDirectory($ftp_conn, '/path/to/directory');

ftp_close($ftp_conn);