什么大山| 中联办是什么级别| 女人没有白带说明什么| 粉色象征着什么| 苯三酚注射有什么用| 共济会是什么| 实性结节什么意思| 病人说胡话是什么征兆| 头出汗是什么原因| 农历7月28日是什么星座| 紫荆花代表什么生肖| 经常感冒是什么原因| 心率130左右意味着什么| 尖锐湿疣什么症状| 查宝宝五行八字缺什么| 先兆临产是什么意思| 糖醋鱼用什么鱼做好吃| 世界上最毒的蜘蛛叫什么| 直径是什么意思| 外婆菜是什么菜做的| 梦见家里死人了代表什么预兆| 脚为什么会发麻| 脑花是什么东西| 追逐是什么意思| 日落西山是什么生肖| 跛脚是什么意思| 身上长癣是什么原因引起的| 音调是由什么决定的| 罗汉果是什么| 五月十三号是什么日子| 肾结石什么东西不能吃| 水痘长什么样| 绿壳鸡蛋是什么鸡生的| 蚊虫叮咬用什么药| 乐观是什么意思| 剁椒是什么辣椒| 鸽子夏天喝什么水好| 柠檬不能和什么一起吃| 2006属什么生肖| 吃什么食物对胰腺好| 荷尔蒙是什么东西起什么作用| 蛋蛋冰凉潮湿什么原因| 兵痞是什么意思| 唐僧姓什么| 顺产1-3天吃什么好| 养老金什么时候可以领取| 卵巢是什么| 扁桃体发炎咳嗽吃什么药效果好| 食人鱼长什么样| 检查肝脏应该挂什么科| xswl是什么意思| 胎盘能治什么病| ccu是什么意思| 周杰伦有什么病| 为什么会有床虱| 萎缩性鼻炎用什么药| 快速补血吃什么| 左下腹疼是什么原因| 为什么一直放屁| 手淫过度有什么症状| 蚂蚁属于什么动物| 阴囊上长了几根白毛是什么原因| 为什么会子宫内膜增厚| 什么是化学| 齁是什么意思| 梅干菜是什么菜做的| 紫苏长什么样子图片| 睾丸大是什么原因| 膝盖骨质增生用什么药效果好| 怀孕初期会有什么症状| 史铁生为什么瘫痪| 入围是什么意思| 耐药是什么意思| 中国防御系统叫什么| hpv16有什么症状| 急性肠胃炎吃什么消炎药| 零反式脂肪是什么意思| 苏轼是什么派诗人| 消炎痛又叫什么| 属龙的本命佛是什么佛| stories是什么意思| 坐西向东是什么宅| 兔属什么五行| 拔智齿第二天可以吃什么| 前面有个豹子是什么车| cas是什么意思| 过敏有什么症状表现| 哦多桑是什么意思| 屋尘螨是什么东西| 后背疼吃什么药| bodywash是什么意思| 心慌是什么原因引起的| 结肠多发憩室是什么意思| 用红笔写名字代表什么| 人乳头瘤病毒51型阳性是什么意思| 11年是什么婚| 阴囊上长了几根白毛是什么原因| 测测你天生靠什么吃饭| 心悸是什么感觉| 土龙是什么鱼| 生物工程学什么| 丝状疣挂什么科| 黄墙绿地的作用是什么| 冬瓜有什么功效和作用| 不能喝酒是什么原因| 什么什么多彩| 为什么晚上不能吃姜| 甲胎蛋白偏高是什么原因| 中央党校什么级别| 癫痫是什么| 解落三秋叶的解是什么意思| 肾结石用什么药| 幽门螺杆菌怕什么食物| 垂体分泌什么激素| pr是什么职位| 喉炎是什么原因引起的| yesido是什么意思| 四维空间是什么| 2.21是什么星座| 镜花缘是什么意思| 生物包括什么| 苏打水有什么作用| 瘰疬是什么意思| 肺有问题会出现什么症状| 艾滋病中期有什么症状| 隆科多为什么不姓佟| 什么什么万分| 鼻子突然流血是什么原因| 十一月什么星座| 阳光明媚是什么意思| 5月8号是什么星座| 舌苔发黄是什么原因引起的| 吃什么可以增强硬度| 什么动物是爸爸生的| 排黑便是什么原因| 什么腿| 为什么近视不可逆| 太平猴魁属于什么茶| 梦见猫头鹰是什么预兆| 渣渣辉什么意思| 梦见已故老人是什么预兆| 冲锋什么| 跖疣是什么原因引起的| 阴道炎用什么洗| 胰腺炎的症状是什么| 前列腺炎吃什么食物好| 1971年是什么年| 什么族不吃猪肉| 珊瑚是什么| 海里有什么动物| 女流之辈是什么意思| 无常是什么意思| 猫薄荷是什么东西| 平妻是什么意思| 血糖高的可以吃什么水果| 吃榴莲不能吃什么东西| 熊猫为什么被称为国宝| 哮喘病有什么症状| 三五成群十双在是什么生肖| 白带有血丝是什么原因| 小孩上火了吃什么降火最快| 老公是什么意思| 梦见猪肉是什么意思| 肠粘连吃什么药| 宝宝干咳嗽是什么原因| 蛋白质阴性是什么意思| 天蝎什么象| ly是什么意思| 耳朵嗡嗡响吃什么药| 氨基酸是什么东西| 走之底的字与什么有关| 念珠菌阳性是什么病| 吃什么好排大便| 1为什么读yao| 机油什么牌子的好| 代表什么| 异地办理护照需要什么材料| 武昌鱼是什么鱼| 厥阴是什么意思| 咖啡有什么营养| 继发不孕什么意思| 2月15日什么星座| 什么是有机食品和无机食品| 药流后吃什么消炎药| roger是什么意思| 生姜红糖水有什么作用| 掰弯了是什么意思| 张三李四王五赵六后面是什么| 吃什么东西降尿酸| 九华山在什么地方| 看见双彩虹有什么征兆| 肾结石不能吃什么| 洗牙挂什么科| 晕车的人是什么体质| 黄占读什么| 碰到蛇是什么征兆| 更年期看什么科| 安徽有什么好吃的| 属牛的生什么属相的孩子好| vr眼镜是什么| 鸟几念什么| 感冒头晕是什么原因| 关羽字什么| smile是什么牌子| 什么星空| 蚩尤是什么| 梦见包被偷了什么预兆| 当归什么味道| 备孕需要吃什么| 冰激凌和冰淇淋有什么区别| 人怕出名猪怕壮是什么生肖| 云为什么不会掉下来| 血压低头晕吃什么药| 乳腺癌三期是什么意思| 表姐的儿子叫我什么| 手串断了是什么预兆| 胃不舒服吃什么好| 菊花和金银花一起泡水有什么效果| instagram是什么| 梦见和邻居吵架什么预兆| 牙肿了吃什么消炎药| 舌苔厚是什么原因引起的| 为什么喜欢一个人| 霉菌感染男性什么症状| 4t什么意思| 梭子蟹什么季节吃最好| 中午十二点是什么时辰| 血色素低吃什么补得快| 仙灵脾又叫什么| 口腔溃疡该挂什么科| 两个子是什么字| 下身痒是什么原因| 易建联为什么不打nba| 娃娃鱼用什么呼吸| 断眉有什么说法| 两毛四是什么军衔| 甲状腺偏高有什么影响| 药流前需要做什么检查| 食物中毒呕吐吃什么药| 阴道放气是什么原因| 小孩掉头发是什么原因| 属牛跟什么属相最配| 7个月的宝宝吃什么辅食| 二尖瓣轻度反流是什么意思| 办护照需要带什么| 5月7号是什么星座| 小候鸟是什么意思| black什么颜色| 吃什么白头发变黑| 女生有喉结是什么原因| 报恩是什么意思| 脑梗吃什么药最好| 大麦是什么粮食| 根基是什么意思| 脚气缺什么维生素| 拉红色的屎是什么原因| 三湖慈鲷可以和什么鱼混养| 缺钾什么症状| 捉奸什么意思| 甲亢查什么| 朴实无华是什么意思| ia是什么意思| 尿酸高是什么原因造成的| 带状疱疹是什么病| 百度
Skip to content

t-tera/php-zip

?
?

Repository files navigation

PhpZip

PhpZip is a php-library for extended work with ZIP-archives.

Packagist Version Packagist Downloads Code Coverage Build Status License

Russian Documentation

Versions & Dependencies

Version PHP Documentation
^4.0 (master) ^7.4|^8.0 current
^3.0 ^5.5|^7.0 Docs v3.3

Table of contents

Features

  • Opening and unzipping zip files.
  • Creating ZIP-archives.
  • Modifying ZIP archives.
  • Pure php (not require extension php-zip and class \ZipArchive).
  • It supports saving the archive to a file, outputting the archive to the browser, or outputting it as a string without saving it to a file.
  • Archival comments and comments of individual entry are supported.
  • Get information about each entry in the archive.
  • Only the following compression methods are supported:
    • No compressed (Stored).
    • Deflate compression.
    • BZIP2 compression with the extension php-bz2.
  • Support for ZIP64 (file size is more than 4 GB or the number of entries in the archive is more than 65535).
  • Working with passwords

    Attention!

    For 32-bit systems, the Traditional PKWARE Encryption (ZipCrypto) encryption method is not currently supported. Use the encryption method WinZIP AES Encryption, whenever possible.

    • Set the password to read the archive for all entries or only for some.
    • Change the password for the archive, including for individual entries.
    • Delete the archive password for all or individual entries.
    • Set the password and/or the encryption method, both for all, and for individual entries in the archive.
    • Set different passwords and encryption methods for different entries.
    • Delete the password for all or some entries.
    • Support Traditional PKWARE Encryption (ZipCrypto) and WinZIP AES Encryption encryption methods.
    • Set the encryption method for all or individual entries in the archive.

Requirements

  • PHP >= 7.4 or PHP >= 8.0 (preferably 64-bit).
  • Optional php-extension bzip2 for BZIP2 compression.
  • Optional php-extension openssl for WinZip Aes Encryption support.

Installation

composer require nelexa/zip

Latest stable version: Latest Stable Version

Examples

// create new archive
$zipFile = new \PhpZip\ZipFile();
try{
    $zipFile
        ->addFromString('zip/entry/filename', 'Is file content') // add an entry from the string
        ->addFile('/path/to/file', 'data/tofile') // add an entry from the file
        ->addDir(__DIR__, 'to/path/') // add files from the directory
        ->saveAsFile($outputFilename) // save the archive to a file
        ->close(); // close archive
            
    // open archive, extract, add files, set password and output to browser.
    $zipFile
        ->openFile($outputFilename) // open archive from file
        ->extractTo($outputDirExtract) // extract files to the specified directory
        ->deleteFromRegex('~^\.~') // delete all hidden (Unix) files
        ->addFromString('dir/file.txt', 'Test file') // add a new entry from the string
        ->setPassword('password') // set password for all entries
        ->outputAsAttachment('library.jar'); // output to the browser without saving to a file
}
catch(\PhpZip\Exception\ZipException $e){
    // handle exception
}
finally{
    $zipFile->close();
}

Other examples can be found in the tests/ folder

Glossary

Zip Entry - file or folder in a ZIP-archive. Each entry in the archive has certain properties, for example: file name, compression method, encryption method, file size before compression, file size after compression, CRC32 and others.

Documentation:

Overview of methods of the class \PhpZip\ZipFile

Creation/Opening of ZIP-archive

ZipFile::__construct**

Initializes the ZIP archive

$zipFile = new \PhpZip\ZipFile();
ZipFile::openFile

Opens a zip-archive from a file.

$zipFile = new \PhpZip\ZipFile();
$zipFile->openFile('file.zip');
ZipFile::openFromString

Opens a zip-archive from a string.

$zipFile = new \PhpZip\ZipFile();
$zipFile->openFromString($stringContents);
ZipFile::openFromStream

Opens a zip-archive from the stream.

$stream = fopen('file.zip', 'rb');

$zipFile = new \PhpZip\ZipFile();
$zipFile->openFromStream($stream);

Reading entries from the archive

ZipFile::count

Returns the number of entries in the archive.

$zipFile = new \PhpZip\ZipFile();

$count = count($zipFile);
// or
$count = $zipFile->count();
ZipFile::getListFiles

Returns list of archive files.

$zipFile = new \PhpZip\ZipFile();
$listFiles = $zipFile->getListFiles();

// example array contents:
// array (
//   0 => 'info.txt',
//   1 => 'path/to/file.jpg',
//   2 => 'another path/',
//   3 => '0',
// )
ZipFile::getEntryContent

Returns the entry contents using its name.

// $entryName = 'path/to/example-entry-name.txt';
$zipFile = new \PhpZip\ZipFile();

$contents = $zipFile[$entryName];
// or
$contents = $zipFile->getEntryContents($entryName);
ZipFile::hasEntry

Checks if there is an entry in the archive.

// $entryName = 'path/to/example-entry-name.txt';
$zipFile = new \PhpZip\ZipFile();

$hasEntry = isset($zipFile[$entryName]);
// or
$hasEntry = $zipFile->hasEntry($entryName);
ZipFile::isDirectory

Checks that the entry in the archive is a directory.

// $entryName = 'path/to/';
$zipFile = new \PhpZip\ZipFile();

$isDirectory = $zipFile->isDirectory($entryName);
ZipFile::extractTo

Extract the archive contents. The directory must exist.

$zipFile = new \PhpZip\ZipFile();
$zipFile->extractTo($directory);

Extract some files to the directory. The directory must exist.

// $toDirectory = '/tmp';
$extractOnlyFiles = [
    'filename1', 
    'filename2', 
    'dir/dir/dir/'
];
$zipFile = new \PhpZip\ZipFile();
$zipFile->extractTo($toDirectory, $extractOnlyFiles);

Iterating entries

ZipFile is an iterator. Can iterate all the entries in the foreach loop.

foreach($zipFile as $entryName => $contents){
    echo "Filename: $entryName" . PHP_EOL;
    echo "Contents: $contents" . PHP_EOL;
    echo '-----------------------------' . PHP_EOL;
}

Can iterate through the Iterator.

$iterator = new \ArrayIterator($zipFile);
while ($iterator->valid())
{
    $entryName = $iterator->key();
    $contents = $iterator->current();

    echo "Filename: $entryName" . PHP_EOL;
    echo "Contents: $contents" . PHP_EOL;
    echo '-----------------------------' . PHP_EOL;

    $iterator->next();
}

Getting information about entries

ZipFile::getArchiveComment

Returns the Zip archive comment.

$zipFile = new \PhpZip\ZipFile();
$commentArchive = $zipFile->getArchiveComment();
ZipFile::getEntryComment

Returns the comment of an entry using the entry name.

$zipFile = new \PhpZip\ZipFile();
$commentEntry = $zipFile->getEntryComment($entryName);

Adding entries to the archive

All methods of adding entries to a ZIP archive allow you to specify a method for compressing content.

The following methods of compression are available:

  • \PhpZip\Constants\ZipCompressionMethod::STORED - no compression
  • \PhpZip\Constants\ZipCompressionMethod::DEFLATED - Deflate compression
  • \PhpZip\Constants\ZipCompressionMethod::BZIP2 - Bzip2 compression with the extension ext-bz2
ZipFile::addFile

Adds a file to a ZIP archive from the given path.

$zipFile = new \PhpZip\ZipFile();
// $file = '...../file.ext'; 
// $entryName = 'file2.ext'
$zipFile->addFile($file);

// you can specify the name of the entry in the archive (if null, then the last component from the file name is used)
$zipFile->addFile($file, $entryName);

// you can specify a compression method
$zipFile->addFile($file, $entryName, \PhpZip\Constants\ZipCompressionMethod::STORED); // No compression
$zipFile->addFile($file, $entryName, \PhpZip\Constants\ZipCompressionMethod::DEFLATED); // Deflate compression
$zipFile->addFile($file, $entryName, \PhpZip\Constants\ZipCompressionMethod::BZIP2); // BZIP2 compression
ZipFile::addSplFile

Adds a \SplFileInfo to a ZIP archive.

// $file = '...../file.ext'; 
// $entryName = 'file2.ext'
$zipFile = new \PhpZip\ZipFile();

$splFile = new \SplFileInfo('README.md');

$zipFile->addSplFile($splFile);
$zipFile->addSplFile($splFile, $entryName);
// or
$zipFile[$entryName] = new \SplFileInfo($file);

// set compression method
$zipFile->addSplFile($splFile, $entryName, $options = [
    \PhpZip\Constants\ZipOptions::COMPRESSION_METHOD => \PhpZip\Constants\ZipCompressionMethod::DEFLATED,
]);
ZipFile::addFromFinder

Adds files from the Symfony\Component\Finder\Finder to a ZIP archive.

$finder = new \Symfony\Component\Finder\Finder();
$finder
    ->files()
    ->name('*.{jpg,jpeg,gif,png}')
    ->name('/^[0-9a-f]\./')
    ->contains('/lorem\s+ipsum$/i')
    ->in('path');

$zipFile = new \PhpZip\ZipFile();
$zipFile->addFromFinder($finder, $options = [
    \PhpZip\Constants\ZipOptions::COMPRESSION_METHOD => \PhpZip\Constants\ZipCompressionMethod::DEFLATED,
    \PhpZip\Constants\ZipOptions::MODIFIED_TIME => new \DateTimeImmutable('-1 day 5 min')
]);
ZipFile::addFromString

Adds a file to a ZIP archive using its contents.

$zipFile = new \PhpZip\ZipFile();

$zipFile[$entryName] = $contents;
// or
$zipFile->addFromString($entryName, $contents);

// you can specify a compression method
$zipFile->addFromString($entryName, $contents, \PhpZip\Constants\ZipCompressionMethod::STORED); // No compression
$zipFile->addFromString($entryName, $contents, \PhpZip\Constants\ZipCompressionMethod::DEFLATED); // Deflate compression
$zipFile->addFromString($entryName, $contents, \PhpZip\Constants\ZipCompressionMethod::BZIP2); // BZIP2 compression
ZipFile::addFromStream

Adds an entry from the stream to the ZIP archive.

$zipFile = new \PhpZip\ZipFile();
// $stream = fopen(..., 'rb');

$zipFile->addFromStream($stream, $entryName);
// or
$zipFile[$entryName] = $stream;

// you can specify a compression method
$zipFile->addFromStream($stream, $entryName, \PhpZip\Constants\ZipCompressionMethod::STORED); // No compression
$zipFile->addFromStream($stream, $entryName, \PhpZip\Constants\ZipCompressionMethod::DEFLATED); // Deflate compression
$zipFile->addFromStream($stream, $entryName, \PhpZip\Constants\ZipCompressionMethod::BZIP2); // BZIP2 compression
ZipFile::addEmptyDir

Add a new directory.

$zipFile = new \PhpZip\ZipFile();
// $path = "path/to/";
$zipFile->addEmptyDir($path);
// or
$zipFile[$path] = null;
ZipFile::addAll

Adds all entries from an array.

$entries = [
    'file.txt' => 'file contents', // add an entry from the string contents
    'empty dir/' => null, // add empty directory
    'path/to/file.jpg' => fopen('..../filename', 'rb'), // add an entry from the stream
    'path/to/file.dat' => new \SplFileInfo('..../filename'), // add an entry from the file
];

$zipFile = new \PhpZip\ZipFile();
$zipFile->addAll($entries);
ZipFile::addDir

Adds files to the archive from the directory on the specified path without subdirectories.

$zipFile = new \PhpZip\ZipFile();
$zipFile->addDir($dirName);

// you can specify the path in the archive to which you want to put entries
$localPath = 'to/path/';
$zipFile->addDir($dirName, $localPath);

// you can specify a compression method
$zipFile->addDir($dirName, $localPath, \PhpZip\Constants\ZipCompressionMethod::STORED); // No compression
$zipFile->addDir($dirName, $localPath, \PhpZip\Constants\ZipCompressionMethod::DEFLATED); // Deflate compression
$zipFile->addDir($dirName, $localPath, \PhpZip\Constants\ZipCompressionMethod::BZIP2); // BZIP2 compression
ZipFile::addDirRecursive

Adds files to the archive from the directory on the specified path with subdirectories.

$zipFile = new \PhpZip\ZipFile();
$zipFile->addDirRecursive($dirName);

// you can specify the path in the archive to which you want to put entries
$localPath = 'to/path/';
$zipFile->addDirRecursive($dirName, $localPath);

// you can specify a compression method
$zipFile->addDirRecursive($dirName, $localPath, \PhpZip\Constants\ZipCompressionMethod::STORED); // No compression
$zipFile->addDirRecursive($dirName, $localPath, \PhpZip\Constants\ZipCompressionMethod::DEFLATED); // Deflate compression
$zipFile->addDirRecursive($dirName, $localPath, \PhpZip\Constants\ZipCompressionMethod::BZIP2); // BZIP2 compression
ZipFile::addFilesFromIterator

Adds files from the iterator of directories.

// $directoryIterator = new \DirectoryIterator($dir); // without subdirectories
// $directoryIterator = new \RecursiveDirectoryIterator($dir); // with subdirectories
$zipFile = new \PhpZip\ZipFile();
$zipFile->addFilesFromIterator($directoryIterator);

// you can specify the path in the archive to which you want to put entries
$localPath = 'to/path/';
$zipFile->addFilesFromIterator($directoryIterator, $localPath);
// or
$zipFile[$localPath] = $directoryIterator;

// you can specify a compression method
$zipFile->addFilesFromIterator($directoryIterator, $localPath, \PhpZip\Constants\ZipCompressionMethod::STORED); // No compression
$zipFile->addFilesFromIterator($directoryIterator, $localPath, \PhpZip\Constants\ZipCompressionMethod::DEFLATED); // Deflate compression
$zipFile->addFilesFromIterator($directoryIterator, $localPath, \PhpZip\Constants\ZipCompressionMethod::BZIP2); // BZIP2 compression

Example with some files ignoring:

$ignoreFiles = [
    'file_ignore.txt', 
    'dir_ignore/sub dir ignore/'
];

// $directoryIterator = new \DirectoryIterator($dir); // without subdirectories
// $directoryIterator = new \RecursiveDirectoryIterator($dir); // with subdirectories
// use \PhpZip\Util\Iterator\IgnoreFilesFilterIterator for non-recursive search
 
$zipFile = new \PhpZip\ZipFile();
$ignoreIterator = new \PhpZip\Util\Iterator\IgnoreFilesRecursiveFilterIterator(
    $directoryIterator, 
    $ignoreFiles
);

$zipFile->addFilesFromIterator($ignoreIterator);
ZipFile::addFilesFromGlob

Adds files from a directory by glob pattern without subdirectories.

$globPattern = '**.{jpg,jpeg,png,gif}'; // example glob pattern -> add all .jpg, .jpeg, .png and .gif files

$zipFile = new \PhpZip\ZipFile();
$zipFile->addFilesFromGlob($dir, $globPattern);

// you can specify the path in the archive to which you want to put entries
$localPath = 'to/path/';
$zipFile->addFilesFromGlob($dir, $globPattern, $localPath);

// you can specify a compression method
$zipFile->addFilesFromGlob($dir, $globPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::STORED); // No compression
$zipFile->addFilesFromGlob($dir, $globPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::DEFLATED); // Deflate compression
$zipFile->addFilesFromGlob($dir, $globPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::BZIP2); // BZIP2 compression
ZipFile::addFilesFromGlobRecursive

Adds files from a directory by glob pattern with subdirectories.

$globPattern = '**.{jpg,jpeg,png,gif}'; // example glob pattern -> add all .jpg, .jpeg, .png and .gif files

$zipFile = new \PhpZip\ZipFile();
$zipFile->addFilesFromGlobRecursive($dir, $globPattern);

// you can specify the path in the archive to which you want to put entries
$localPath = 'to/path/';
$zipFile->addFilesFromGlobRecursive($dir, $globPattern, $localPath);

// you can specify a compression method
$zipFile->addFilesFromGlobRecursive($dir, $globPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::STORED); // No compression
$zipFile->addFilesFromGlobRecursive($dir, $globPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::DEFLATED); // Deflate compression
$zipFile->addFilesFromGlobRecursive($dir, $globPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::BZIP2); // BZIP2 compression
ZipFile::addFilesFromRegex

Adds files from a directory by PCRE pattern without subdirectories.

$regexPattern = '/\.(jpe?g|png|gif)$/si'; // example regex pattern -> add all .jpg, .jpeg, .png and .gif files

$zipFile = new \PhpZip\ZipFile();
$zipFile->addFilesFromRegex($dir, $regexPattern);

// you can specify the path in the archive to which you want to put entries
$localPath = 'to/path/';
$zipFile->addFilesFromRegex($dir, $regexPattern, $localPath);

// you can specify a compression method
$zipFile->addFilesFromRegex($dir, $regexPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::STORED); // No compression
$zipFile->addFilesFromRegex($dir, $regexPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::DEFLATED); // Deflate compression
$zipFile->addFilesFromRegex($dir, $regexPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::BZIP2); // BZIP2 compression
ZipFile::addFilesFromRegexRecursive

Adds files from a directory by PCRE pattern with subdirectories.

$regexPattern = '/\.(jpe?g|png|gif)$/si'; // example regex pattern -> add all .jpg, .jpeg, .png and .gif files

$zipFile->addFilesFromRegexRecursive($dir, $regexPattern);

// you can specify the path in the archive to which you want to put entries
$localPath = 'to/path/';
$zipFile->addFilesFromRegexRecursive($dir, $regexPattern, $localPath);

// you can specify a compression method
$zipFile->addFilesFromRegexRecursive($dir, $regexPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::STORED); // No compression
$zipFile->addFilesFromRegexRecursive($dir, $regexPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::DEFLATED); // Deflate compression
$zipFile->addFilesFromRegexRecursive($dir, $regexPattern, $localPath, \PhpZip\Constants\ZipCompressionMethod::BZIP2); // BZIP2 compression

Deleting entries from the archive

ZipFile::deleteFromName

Deletes an entry in the archive using its name.

$zipFile = new \PhpZip\ZipFile();
$zipFile->deleteFromName($entryName);
ZipFile::deleteFromGlob

Deletes a entries in the archive using glob pattern.

$globPattern = '**.{jpg,jpeg,png,gif}'; // example glob pattern -> delete all .jpg, .jpeg, .png and .gif files

$zipFile = new \PhpZip\ZipFile();
$zipFile->deleteFromGlob($globPattern);
ZipFile::deleteFromRegex

Deletes a entries in the archive using PCRE pattern.

$regexPattern = '/\.(jpe?g|png|gif)$/si'; // example regex pattern -> delete all .jpg, .jpeg, .png and .gif files

$zipFile = new \PhpZip\ZipFile();
$zipFile->deleteFromRegex($regexPattern);
ZipFile::deleteAll

Deletes all entries in the ZIP archive.

$zipFile = new \PhpZip\ZipFile();
$zipFile->deleteAll();

Working with entries and archive

ZipFile::rename

Renames an entry defined by its name.

$zipFile = new \PhpZip\ZipFile();
$zipFile->rename($oldName, $newName);
ZipFile::setCompressionLevel

Set the compression level for all files in the archive.

Note that this method does not apply to entries that are added after this method is run.

By default, the compression level is 5 (\PhpZip\Constants\ZipCompressionLevel::NORMAL) or the compression level specified in the archive for Deflate compression.

The values range from 1 (\PhpZip\Constants\ZipCompressionLevel::SUPER_FAST) to 9 (\PhpZip\Constants\ZipCompressionLevel::MAXIMUM) are supported. The higher the number, the better and longer the compression.

$zipFile = new \PhpZip\ZipFile();
$zipFile->setCompressionLevel(\PhpZip\Constants\ZipCompressionLevel::MAXIMUM);
ZipFile::setCompressionLevelEntry

Sets the compression level for the entry by its name.

The values range from 1 (\PhpZip\Constants\ZipCompressionLevel::SUPER_FAST) to 9 (\PhpZip\Constants\ZipCompressionLevel::MAXIMUM) are supported. The higher the number, the better and longer the compression.

$zipFile = new \PhpZip\ZipFile();
$zipFile->setCompressionLevelEntry($entryName, \PhpZip\Constants\ZipCompressionLevel::FAST);
ZipFile::setCompressionMethodEntry

Sets the compression method for the entry by its name.

The following compression methods are available:

  • \PhpZip\Constants\ZipCompressionMethod::STORED - No compression
  • \PhpZip\Constants\ZipCompressionMethod::DEFLATED - Deflate compression
  • \PhpZip\Constants\ZipCompressionMethod::BZIP2 - Bzip2 compression with the extension ext-bz2
$zipFile = new \PhpZip\ZipFile();
$zipFile->setCompressionMethodEntry($entryName, \PhpZip\Constants\ZipCompressionMethod::DEFLATED);
ZipFile::setArchiveComment

Set the comment of a ZIP archive.

$zipFile = new \PhpZip\ZipFile();
$zipFile->setArchiveComment($commentArchive);
ZipFile::setEntryComment

Set the comment of an entry defined by its name.

$zipFile = new \PhpZip\ZipFile();
$zipFile->setEntryComment($entryName, $comment);
ZipFile::matcher

Selecting entries in the archive to perform operations on them.

$zipFile = new \PhpZip\ZipFile();
$matcher = $zipFile->matcher();

Selecting files from the archive one at a time:

$matcher
    ->add('entry name')
    ->add('another entry');

Select multiple files in the archive:

$matcher->add([
    'entry name',
    'another entry name',
    'path/'
]);

Selecting files by regular expression:

$matcher->match('~\.jpe?g$~i');

Select all files in the archive:

$matcher->all();

count() - gets the number of selected entries:

$count = count($matcher);
// or
$count = $matcher->count();

getMatches() - returns a list of selected entries:

$entries = $matcher->getMatches();
// example array contents: ['entry name', 'another entry name'];

invoke() - invoke a callable function on selected entries:

// example
$matcher->invoke(static function($entryName) use($zipFile) {
    $newName = preg_replace('~\.(jpe?g)$~i', '.no_optimize.$1', $entryName);
    $zipFile->rename($entryName, $newName);
});

Functions for working on the selected entries:

$matcher->delete(); // remove selected entries from a ZIP archive
$matcher->setPassword($password); // sets a new password for the selected entries
$matcher->setPassword($password, $encryptionMethod); // sets a new password and encryption method to selected entries
$matcher->setEncryptionMethod($encryptionMethod); // sets the encryption method to the selected entries
$matcher->disableEncryption(); // disables encryption for selected entries

Working with passwords

Implemented support for encryption methods:

  • \PhpZip\Constants\ZipEncryptionMethod::PKWARE - Traditional PKWARE encryption (legacy)
  • \PhpZip\Constants\ZipEncryptionMethod::WINZIP_AES_256 - WinZip AES encryption 256 bit (recommended)
  • \PhpZip\Constants\ZipEncryptionMethod::WINZIP_AES_192 - WinZip AES encryption 192 bit
  • \PhpZip\Constants\ZipEncryptionMethod::WINZIP_AES_128 - WinZip AES encryption 128 bit
ZipFile::setReadPassword

Set the password for the open archive.

Setting a password is not required for adding new entries or deleting existing ones, but if you want to extract the content or change the method / compression level, the encryption method, or change the password, in this case the password must be specified.

$zipFile->setReadPassword($password);
ZipFile::setReadPasswordEntry

Gets a password for reading of an entry defined by its name.

$zipFile->setReadPasswordEntry($entryName, $password);
ZipFile::setPassword

Sets a new password for all files in the archive.

Note that this method does not apply to entries that are added after this method is run.

$zipFile->setPassword($password);

You can set the encryption method:

$encryptionMethod = \PhpZip\Constants\ZipEncryptionMethod::WINZIP_AES_256;
$zipFile->setPassword($password, $encryptionMethod);
ZipFile::setPasswordEntry

Sets a new password of an entry defined by its name.

$zipFile->setPasswordEntry($entryName, $password);

You can set the encryption method:

$encryptionMethod = \PhpZip\Constants\ZipEncryptionMethod::WINZIP_AES_256;
$zipFile->setPasswordEntry($entryName, $password, $encryptionMethod);
ZipFile::disableEncryption

Disable encryption for all entries that are already in the archive.

Note that this method does not apply to entries that are added after this method is run.

$zipFile->disableEncryption();
ZipFile::disableEncryptionEntry

Disable encryption of an entry defined by its name.

$zipFile->disableEncryptionEntry($entryName);

Undo changes

ZipFile::unchangeAll

Undo all changes done in the archive.

$zipFile->unchangeAll();
ZipFile::unchangeArchiveComment

Undo changes to the archive comment.

$zipFile->unchangeArchiveComment();
ZipFile::unchangeEntry

Undo changes of an entry defined by its name.

$zipFile->unchangeEntry($entryName);

Saving a file or output to a browser

ZipFile::saveAsFile

Saves the archive to a file.

$zipFile->saveAsFile($filename);
ZipFile::saveAsStream

Writes the archive to the stream.

// $fp = fopen($filename, 'w+b');

$zipFile->saveAsStream($fp);
ZipFile::outputAsString

Outputs a ZIP-archive as string.

$rawZipArchiveBytes = $zipFile->outputAsString();
ZipFile::outputAsAttachment

Outputs a ZIP-archive to the browser.

$zipFile->outputAsAttachment($outputFilename);

You can set the Mime-Type:

$mimeType = 'application/zip';
$zipFile->outputAsAttachment($outputFilename, $mimeType);
ZipFile::outputAsPsr7Response

Outputs a ZIP-archive as PSR-7 Response.

The output method can be used in any PSR-7 compatible framework.

// $response = ....; // instance Psr\Http\Message\ResponseInterface
$zipFile->outputAsPsr7Response($response, $outputFilename);

You can set the Mime-Type:

$mimeType = 'application/zip';
$zipFile->outputAsPsr7Response($response, $outputFilename, $mimeType);
ZipFile::outputAsSymfonyResponse

Outputs a ZIP-archive as Symfony Response.

The output method can be used in Symfony framework.

$response = $zipFile->outputAsSymfonyResponse($outputFilename);

You can set the Mime-Type:

$mimeType = 'application/zip';
$response = $zipFile->outputAsSymfonyResponse($outputFilename, $mimeType);

Example use in Symfony Controller:

<?php

namespace App\Controller;

use PhpZip\ZipFile;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class DownloadZipController
{
    /**
     * @Route("/downloads/{id}")
     *
     * @throws \PhpZip\Exception\ZipException
     */
    public function __invoke(string $id): Response
    {
        $zipFile = new ZipFile();
        $zipFile['file'] = 'contents';

        $outputFilename = $id . '.zip';
        return $zipFile->outputAsSymfonyResponse($outputFilename);
    }
}
ZipFile::rewrite

Save changes and re-open the changed archive.

$zipFile->rewrite();

Closing the archive

ZipFile::close

Close the archive.

$zipFile->close();

Running the tests

Install the dependencies for the development:

composer install --dev

Run the tests:

vendor/bin/phpunit

Changelog

Changes are documented in the releases page.

Upgrade

Upgrade version 3 to version 4

Update the major version in the file composer.json to ^4.0.

{
    "require": {
        "nelexa/zip": "^4.0"
    }
}

Then install updates using Composer:

composer update nelexa/zip

Update your code to work with the new version: BC

  • removed deprecated classes and methods.
  • removed zipalign functional. This functionality will be placed in a separate package nelexa/apkfile.

Upgrade version 2 to version 3

Update the major version in the file composer.json to ^3.0.

{
    "require": {
        "nelexa/zip": "^3.0"
    }
}

Then install updates using Composer:

composer update nelexa/zip

Update your code to work with the new version:

  • Class ZipOutputFile merged to ZipFile and removed.
    • new \PhpZip\ZipOutputFile() to new \PhpZip\ZipFile()
  • Static initialization methods are now not static.
    • \PhpZip\ZipFile::openFromFile($filename); to (new \PhpZip\ZipFile())->openFile($filename);
    • \PhpZip\ZipOutputFile::openFromFile($filename); to (new \PhpZip\ZipFile())->openFile($filename);
    • \PhpZip\ZipFile::openFromString($contents); to (new \PhpZip\ZipFile())->openFromString($contents);
    • \PhpZip\ZipFile::openFromStream($stream); to (new \PhpZip\ZipFile())->openFromStream($stream);
    • \PhpZip\ZipOutputFile::create() to new \PhpZip\ZipFile()
    • \PhpZip\ZipOutputFile::openFromZipFile(\PhpZip\ZipFile $zipFile) > (new \PhpZip\ZipFile())->openFile($filename);
  • Rename methods:
    • addFromFile to addFile
    • setLevel to setCompressionLevel
    • ZipFile::setPassword to ZipFile::withReadPassword
    • ZipOutputFile::setPassword to ZipFile::withNewPassword
    • ZipOutputFile::disableEncryptionAllEntries to ZipFile::withoutPassword
    • ZipOutputFile::setComment to ZipFile::setArchiveComment
    • ZipFile::getComment to ZipFile::getArchiveComment
  • Changed signature for methods addDir, addFilesFromGlob, addFilesFromRegex.
  • Remove methods:
    • getLevel
    • setCompressionMethod
    • setEntryPassword

About

PhpZip is a php-library for extended work with ZIP-archives.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • PHP 100.0%
夏天中暑吃什么药 胃息肉有什么危害 运动裤配什么上衣好看 豆工念什么 得了幽门螺杆菌是什么症状
观音土是什么 2035年是什么年 浮瓜沉李什么意思 子宫内膜薄有什么危害 龋齿挂什么科
牛鞭是什么东西 手麻疼是什么原因引起 口臭挂什么科 打嗝不停是什么病前兆 眼睛飞蚊症用什么药能治好
4级残疾证有什么优惠政策 腰椎间盘突出和膨出有什么区别 金鱼可以吃什么 人体最大的排毒器官是什么 脂肪肝是什么原因造成的
女士喝什么茶叶对身体好hcv8jop7ns7r.cn 7月19号是什么星座tiangongnft.com 咨询什么意思hcv9jop2ns0r.cn b超是检查什么的bysq.com 气血虚什么症状hcv9jop5ns0r.cn
蓝本是什么意思hcv8jop7ns4r.cn 生性凉薄是什么意思hcv8jop8ns2r.cn 会厌炎是什么病jinxinzhichuang.com 青少年膝盖痛什么原因hcv9jop3ns0r.cn 孕妇缺维生素D对胎儿有什么影响hcv8jop3ns9r.cn
大理寺卿是什么职位kuyehao.com 人尽可夫是什么意思hcv9jop4ns3r.cn 请佛像回家有什么讲究hcv9jop0ns9r.cn 用什么药膏能拔去粉瘤hcv8jop8ns4r.cn 动脉瘤是什么hcv9jop2ns4r.cn
儿童乘坐高铁需要什么证件hcv8jop5ns9r.cn 抉择是什么意思shenchushe.com 皮肤软组织感染用什么消炎药hcv7jop9ns7r.cn 长期贫血会导致什么严重后果hcv8jop7ns6r.cn 脚气是什么菌引起的hcv8jop2ns6r.cn
百度