Home > Article > Backend Development > How to compress and decompress files on FTP server via PHP
How to compress and decompress files on an FTP server through PHP
Introduction:
In the process of developing and managing websites, we often need to handle file compression and decompression operations. And if the website's file storage uses an FTP server, how to compress and decompress files through PHP on the server becomes a key issue. This article will introduce how to compress and decompress files on an FTP server through PHP, and provide relevant code examples for reference.
$ftp_server = "ftp.example.com"; $ftp_user = "username"; $ftp_pass = "password"; // 连接到FTP服务器 $conn = ftp_connect($ftp_server); if (!$conn) { die("无法连接到FTP服务器"); } // 登录到FTP服务器 $login = ftp_login($conn, $ftp_user, $ftp_pass); if (!$login) { die("登录失败"); } // 设置FTP模式为被动模式 ftp_pasv($conn, true);
$zip_file = "compressed.zip"; $file_to_compress = "file_to_compress.txt"; // 创建一个新的ZIP文件 $zip = new ZipArchive(); if ($zip->open($zip_file, ZipArchive::CREATE) !== true) { die("无法创建ZIP文件"); } // 将文件添加到ZIP文件中 $zip->addFile($file_to_compress); // 关闭ZIP文件 $zip->close(); // 将压缩文件上传到FTP服务器 if (ftp_put($conn, $zip_file, $zip_file, FTP_BINARY)) { echo "文件已成功压缩并上传到FTP服务器"; } else { echo "文件压缩失败"; } // 删除本地的压缩文件 unlink($zip_file);
$zip_file = "compressed.zip"; $unzip_folder = "unzipped_files"; // 从FTP服务器下载压缩文件 if (ftp_get($conn, $zip_file, $zip_file, FTP_BINARY)) { echo "压缩文件已成功下载到本地"; } else { echo "下载压缩文件失败"; } // 创建一个新的ZIP文件 $zip = new ZipArchive(); if ($zip->open($zip_file) === true) { // 解压缩ZIP文件到指定目录 $zip->extractTo($unzip_folder); $zip->close(); echo "文件已成功解压缩到指定目录"; } else { echo "解压缩文件失败"; } // 删除本地的压缩文件 unlink($zip_file);
Summary:
Through the above code example, we can see how to use PHP to implement files on an FTP server compression and decompression operations. This can provide great convenience for our website development and file management. Of course, in actual use, the code needs to be further improved and adjusted according to specific needs to adapt to different scenarios. I hope this article can provide some reference and help for you to perform file compression and decompression operations on the FTP server.
The above is the detailed content of How to compress and decompress files on FTP server via PHP. For more information, please follow other related articles on the PHP Chinese website!