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);
?>
Keywords
Related Questions
- In what situations should variables be accessed using the $_POST superglobal array instead of directly referencing them in PHP scripts to avoid errors and improve code reliability?
- How can one manually download and install MCRYPT in PHP after encountering an error related to its absence?
- What are the implications of a hosting provider having register_globals set to off in the php.ini file?