PHP ziparchive is the extension class PHP, you can easily realize the zip file compression and decompression, the first to ensure that the PHP zip extension has been opened, the specific way to open this is not said, different platforms to open the method of expansion of PHP online have, if there are questions to welcome the exchange. Here to organize the use of PHP ziparchive file compression and decompression of the common examples for reference.
first, unzip the zip file
$zip =new ziparchive;//Creates a new Ziparchive object
if ($zip->open (' Test.zip ') ===true) {
$zip->extractto (' Images ')//Suppose uncompressed to the images folder within the current path
$zip->close ();//close processing zip file
}
Compress the file into zip file
$zip =new ziparchive;
if ($zip->open (' Test.zip ', ziparchive::overwrite) ===true) {
$zip->addfile (' image.txt '); Suppose the filename added is image.txt,
$zip->close () under the current path;
Third, file additions 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 ';
Pack the folders into zip files
function Addfiletozip ($path, $zip) {
$handler =opendir ($path);//Open current folder specified by $path. While
(($filename =readdir ($handler))!==false) {
if ($filename!= "." && $filename!= "...") The {//folder file name is '. ' and '.. ', do not manipulate them
if (Is_dir ($path.) /". $filename)) {//If one of the objects read is a folder, recursion
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 method, operate on the root directory to be packaged and pass the Ziparchive object to the method
$zip->close ();//Close the processed zip file
The above is the PHP implementation of the file compression and decompression of the four different situations, there may be other circumstances did not complement the complete, in the post after the update, I hope this article for everyone's learning help.