Are there any specific PHP functions or libraries that are recommended for handling directory compression and transfer tasks?
When handling directory compression and transfer tasks in PHP, it is recommended to use the ZipArchive class for compressing directories and the FTP functions for transferring files to a remote server. The ZipArchive class provides an easy way to create zip archives of directories, while the FTP functions allow for transferring files securely over FTP.
// Create a zip archive of a directory
function createZipArchive($source, $destination) {
$zip = new ZipArchive();
if ($zip->open($destination, ZipArchive::CREATE) !== TRUE) {
die("Cannot create zip archive");
}
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
$file = realpath($file);
if (is_dir($file)) {
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} else if (is_file($file)) {
$zip->addFile($file, str_replace($source . '/', '', $file));
}
}
$zip->close();
}
// Transfer the zip archive to a remote server using FTP
function transferZipArchive($source, $destination, $ftp_server, $ftp_user, $ftp_pass) {
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);
if ($login_result) {
if (ftp_put($conn_id, $destination, $source, FTP_BINARY)) {
echo "File transferred successfully";
} else {
echo "Failed to transfer file";
}
} else {
echo "Failed to connect to FTP server";
}
ftp_close($conn_id);
}
// Example usage
$sourceDir = '/path/to/source/dir';
$zipDestination = '/path/to/destination/archive.zip';
$ftpServer = 'ftp.example.com';
$ftpUser = 'username';
$ftpPass = 'password';
createZipArchive($sourceDir, $zipDestination);
transferZipArchive($zipDestination, basename($zipDestination), $ftpServer, $ftpUser, $ftpPass);
Related Questions
- How can passing the FTP connection as a parameter to a PHP function improve code versatility and organization?
- What are the potential risks of relying on the $_SERVER['HTTP_REFERER'] variable in PHP?
- What are the advantages and disadvantages of using POST versus GET methods for deleting entries in a PHP application?