Compress a file
We generate a compressed package from a file.
<?php $path = "c:/wamp/www/log.txt"; $filename = "test.zip"; $zip = new ZipArchive(); $zip->open($filename,ZipArchive::CREATE); //打开压缩包 $zip->addFile($path,basename($path)); //向压缩包中添加文件 $zip->close(); //关闭压缩包
The above code compresses the c:/wamp/www/log.txt file into test.zip and saves it in the current directory.
Related recommendations: "php Getting Started Tutorial"
Compress multiple files
Compressing multiple files is actually addFile Execution multiple times can be achieved by traversing the array.
<?php $fileList = array( "c:/wamp/www/log.txt", "c:/wamp/www/weixin.class.php" ); $filename = "test.zip"; $zip = new ZipArchive(); $zip->open($filename,ZipArchive::CREATE); //打开压缩包 foreach($fileList as $file){ $zip->addFile($file,basename($file)); //向压缩包中添加文件 } $zip->close(); //关闭压缩包
Compress a directory
<?php function addFileToZip($path,$zip){ $handler=opendir($path); //打开当前文件夹由$path指定。 while(($filename=readdir($handler))!==false){ if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作 if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归 addFileToZip($path."/".$filename, $zip); }else{ //将文件加入zip对象 $zip->addFile($path."/".$filename); } } } @closedir($path); } $zip=new ZipArchive(); if($zip->open('rsa.zip', ZipArchive::OVERWRITE)=== TRUE){ addFileToZip('rsa/', $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 $zip->close(); //关闭处理的zip文件 }
Compress and download the zip package
In my case, we need to provide it after packaging Download and then delete the compressed package.
can be divided into the following steps:
(1) Determine whether the given path is a folder or a file. The folder also needs to be traversed to add files.
(2) Set the relevant file header and use the readfile function to provide downloading.
(3) Use the unlink function to delete the compressed package.
<?php function addFileToZip($path,$zip){ $handler=opendir($path); //打开当前文件夹由$path指定。 while(($filename=readdir($handler))!==false){ if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作 if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹,则递归 addFileToZip($path."/".$filename, $zip); }else{ //将文件加入zip对象 $zip->addFile($path."/".$filename); } } } @closedir($path); } $zip=new ZipArchive(); if($zip->open('rsa.zip', ZipArchive::OVERWRITE)=== TRUE){ $path = 'rsa/'; if(is_dir($path)){ //给出文件夹,打包文件夹 addFileToZip($path, $zip); }else if(is_array($path)){ //以数组形式给出文件路径 foreach($path as $file){ $zip->addFile($file); } }else{ //只给出一个文件 $zip->addFile($path); } $zip->close(); //关闭处理的zip文件 }
The above is the detailed content of How to compress files in php. For more information, please follow other related articles on the PHP Chinese website!