PHP extension class ZipArchive is easy to use
Aug 08, 2016 am 09:23 AM1. Unzip the zip file
<?php $zip = new ZipArchive;//新建一个ZipArchive的对象 /* 通过ZipArchive的对象处理zip文件 $zip->open这个方法的参数表示处理的zip文件名。 如果对zip文件对象操作成功,$zip->open这个方法会返回TRUE */ if ($zip->open('test.zip') === TRUE){ $zip->extractTo('images');//假设解压缩到在当前路径下images文件夹的子文件夹php $zip->close();//关闭处理的zip文件 } ?>
<?php $zip = new ZipArchive; /* $zip->open这个方法第一个参数表示处理的zip文件名。 第二个参数表示处理模式,ZipArchive::OVERWRITE表示如果zip文件存在,就覆盖掉原来的zip文件。 如果参数使用ZIPARCHIVE::CREATE,系统就会往原来的zip文件里添加内容。 如果不是为了多次添加内容到zip文件,建议使用ZipArchive::OVERWRITE。 使用这两个参数,如果zip文件不存在,系统都会自动新建。 如果对zip文件对象操作成功,$zip->open这个方法会返回TRUE */ if ($zip->open('test.zip', ZipArchive::OVERWRITE) === TRUE){ $zip->addFile('image.txt');//假设加入的文件名是image.txt,在当前路径下 $zip->close(); } ?>
<?php $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. Pack the folder into a zip file
<?php function addFileToZip($path, $zip) { $handler = opendir($path); //打开当前文件夹由$path指定。 /* 循环的读取文件夹下的所有文件和文件夹 其中$filename = readdir($handler)是每次循环的时候将读取的文件名赋值给$filename, 为了不陷于死循环,所以还要让$filename !== false。 一定要用!==,因为如果某个文件名如果叫'0',或者某些被系统认为是代表false,用!=就会停止循环 */ 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('images.zip', ZipArchive::OVERWRITE) === TRUE) { addFileToZip('images/', $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 $zip->close(); //关闭处理的zip文件 } ?>
The above has introduced the simple use of the PHP extension class ZipArchive, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the differences between Huawei GT3 Pro and GT4?

Zip decompression library in PHP8.0: ZipArchive

Solution to PHP Fatal error: Class 'ZipArchive' not found in

Fix: Snipping tool not working in Windows 11

How to use PHP ZipArchive to encrypt and decrypt the file contents of a compressed package?

Best Guide to Compressing HTML Files to ZIP

How to use linux compression zip command

How to Fix Can't Connect to App Store Error on iPhone
