What is the recommended method to compress and backup the contents of an FTP folder using PHP?

To compress and backup the contents of an FTP folder using PHP, you can use the ZipArchive class to create a zip file containing the folder contents. You can then download the zip file to your local machine or store it on the server for backup purposes.

<?php
// Connect to FTP server
$ftp_server = 'ftp.example.com';
$ftp_username = 'username';
$ftp_password = 'password';
$ftp_connection = ftp_connect($ftp_server);
ftp_login($ftp_connection, $ftp_username, $ftp_password);

// Define folder to backup
$ftp_folder = '/path/to/ftp/folder';

// Create a zip file
$zip = new ZipArchive();
$zip_filename = 'backup.zip';
if ($zip->open($zip_filename, ZipArchive::CREATE) === TRUE) {
    // Add files from FTP folder to zip
    $files = ftp_nlist($ftp_connection, $ftp_folder);
    foreach ($files as $file) {
        $zip->addFile("ftp://$ftp_username:$ftp_password@$ftp_server$file", basename($file));
    }
    $zip->close();
}

// Download zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$zip_filename");
readfile($zip_filename);

// Close FTP connection
ftp_close($ftp_connection);
?>