这篇文章主要介绍了php使用ZipArchive函数实现文件的压缩与解压缩,需要的朋友可以参考下
PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法这里就不说了,不同的平台开启PHP扩增的方法网上都有,如有疑问欢迎交流。这里整理一下利用php zipArchive进行文件的压缩与解压缩的常用的示例供参考。
一、解压缩zip文件
$zip=new ZipArchive;//新建一个ZipArchive的对象 if($zip->open('test.zip')===TRUE){ $zip->extractTo('images');//假设解压缩到在当前路径下images文件夹内 $zip->close();//关闭处理的zip文件 }
二、将文件压缩成zip文件
$zip=new ZipArchive; if($zip->open('test.zip',ZipArchive::OVERWRITE)===TRUE){ $zip->addFile('image.txt');//假设加入的文件名是image.txt,在当前路径下 $zip->close(); }
三、文件追加内容添加到zip文件
$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'; }
四、将文件夹打包成zip文件
function addFileToZip($path,$zip){ $handler=opendir($path); //打开当前文件夹由$path指定。 while(($filename=readdir($handler))!==false){ if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..',,不要对他们进行操作 if(is_dir($path."http://www.jb51.net/".$filename)){// 如果读取的某个对象是文件夹,则递归 addFileToZip($path."http://www.jb51.net/".$filename, $zip); }else{ //将文件加入zip对象 $zip->addFile($path."http://www.jb51.net/".$filename); } } } @closedir($path); } $zip=new ZipArchive(); if($zip->open('images.zip', ZipArchive::OVERWRITE)=== TRUE){ addFileToZip('images/', $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 $zip->close(); //关闭处理的zip文件 }
以上就是php实现文件的压缩与解压缩的四种不同情况,可能还有其他情况没有补充完整,在之后的文章中陆续更新,希望这篇文章对大家的学习有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment