Home > Article > Backend Development > How to compress and decompress files on an FTP server through PHP
How to realize file compression and decompression on FTP server through PHP
In the process of web development, FTP server is a commonly used file transfer tool, and file compression and decompression is to reduce file size, An effective way to reduce transfer time. This article will introduce how to compress and decompress files on an FTP server through PHP.
The following is a sample code for a compressed file:
<?php // FTP服务器的连接信息 $ftp_host = '服务器地址'; $ftp_user = '用户名'; $ftp_pass = '密码'; // 要压缩的文件目录及名称 $zip_path = 'path/to/compress'; $zip_name = 'compress.zip'; // 连接到FTP服务器 $ftp = ftp_connect($ftp_host); ftp_login($ftp, $ftp_user, $ftp_pass); // 创建一个ZIP文件 $zip = new ZipArchive; $zip->open($zip_name, ZipArchive::CREATE); // 遍历文件目录,将每个文件添加到ZIP文件中 $files = scandir($zip_path); foreach ($files as $file) { if ($file !== '.' && $file !== '..') { $zip->addFile($zip_path.'/'.$file, $file); } } // 关闭ZIP文件 $zip->close(); // 上传ZIP文件到FTP服务器 ftp_put($ftp, $zip_name, $zip_name, FTP_BINARY); // 关闭FTP连接 ftp_close($ftp); ?>
The following is a sample code to decompress a file:
<?php // FTP服务器的连接信息 $ftp_host = '服务器地址'; $ftp_user = '用户名'; $ftp_pass = '密码'; // 要解压缩的ZIP文件和目标目录 $zip_name = 'compress.zip'; $unzip_path = 'path/to/unzip'; // 连接到FTP服务器 $ftp = ftp_connect($ftp_host); ftp_login($ftp, $ftp_user, $ftp_pass); // 从FTP服务器上下载ZIP文件 ftp_get($ftp, $zip_name, $zip_name, FTP_BINARY); // 解压缩ZIP文件到指定目录 $zip = new ZipArchive; if ($zip->open($zip_name) === TRUE) { $zip->extractTo($unzip_path); $zip->close(); echo '解压缩成功!'; } else { echo '解压缩失败!'; } // 关闭FTP连接 ftp_close($ftp); ?>
The above is how to compress and decompress files on an FTP server through PHP. Using these methods can easily compress and decompress files and achieve high efficiency in file transfer. I hope this article will be helpful to your study and work!
The above is the detailed content of How to compress and decompress files on an FTP server through PHP. For more information, please follow other related articles on the PHP Chinese website!