This article describes how to use the ZipArchive function in php to compress and decompress files. For more information, see PHP ZipArchive, which is an extension class provided by PHP, you can easily compress and decompress the ZIP file. before using it, make sure that the php zip extension has been enabled, methods for enabling PHP amplification on different platforms are available online. if you have any questions, please contact us. Here are some common examples of file compression and decompression using php zipArchive for your reference.
I. decompress the zip file
$ Zip = new ZipArchive; // Create a ZipArchive object if ($ zip-> open('test.zip ') === TRUE) {$ zip-> extraceid ('images '); // suppose you want to decompress the package to $ zip-> close () in the images folder in the current path; // close the processed zip file}
2. compress the file into a zip file
$ Zip = new ZipArchive; if ($ zip-> open('test.zip ', ZipArchive: OVERWRITE) === TRUE) {$ zip-> addFile('image.txt'); // The name of the file to be added is image.txt, in the current path $ zip-> close ();}
3. add the content appended to the zip file
$zip=new ZipArchive; $res=$zip->open('test.zip',ZipArchive::CREATE); if($res===TRUE){ $zip->addFromString('test.txt','file content goes here'); $zip->close(); echo 'ok'; }else{ echo 'failed'; }
4. package folders into zip files
Function addFileToZip ($ path, $ zip) {$ handler = opendir ($ path); // specify $ path to open the current folder. While ($ filename = readdir ($ handler ))! = False) {if ($ filename! = "." & $ Filename! = ".. ") {// The folder name is '. 'and '.. ', do not operate on them if (is_dir ($ path. "/". $ filename) {// recursive addFileToZip ($ path. "/". $ filename, $ zip);} else {// add the file to the zip object $ zip-> addFile ($ path. "/". $ filename) ;}}@ closedir ($ path) ;}$ zip = new ZipArchive (); if ($ zip-> open('images.zip ', ZipArchive: OVERWRITE) === TRUE) {addFileToZip ('images/', $ zip); // call the method to operate the root directory to be packaged, and pass the ZipArchive object to the method $ zip-> close (); // close the processed zip file}
The above are four different cases of file compression and decompression in php. There may be other cases that have not been fully supplemented and will be updated in subsequent articles, I hope this article will be helpful for your learning.