PhpZip — php-библиотека для расширенной работы с ZIP-архивами.
Русская документация
| Версия | PHP | Документация |
|---|---|---|
| ^ 4.0 (мастер) | ^7,4|^8,0 | текущий |
| ^ 3,0 | ^5,5|^7,0 | Документы v3.3 |
PhpZipZipFilephp-zip и класс ZipArchive ).php-bz2 .ZIP64 (размер файла более 4 ГБ или количество записей в архиве более 65535).Внимание!
Для 32-битных систем метод шифрования
Traditional PKWARE Encryption (ZipCrypto)в настоящее время не поддерживается. По возможности используйте метод шифрованияWinZIP AES Encryption.
Traditional PKWARE Encryption (ZipCrypto) и WinZIP AES Encryption .PHP >= 7.4 или PHP >= 8.0 (предпочтительно 64-разрядная версия).bzip2 для сжатия BZIP2.openssl для поддержки WinZip Aes Encryption . composer require nelexa/zip
Последняя стабильная версия:
// 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 ();
} Остальные примеры можно найти в папкеtests tests/ .
Zip Entry — файл или папка в ZIP-архиве. Каждая запись в архиве имеет определенные свойства, например: имя файла, метод сжатия, метод шифрования, размер файла до сжатия, размер файла после сжатия, CRC32 и другие.
PhpZipZipFileSplFileInfo в ZIP-архив.SymfonyComponentFinderFinder в ZIP-архив.Инициализирует ZIP-архив
$ zipFile = new PhpZip ZipFile ();Открывает zip-архив из файла.
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> openFile ( ' file.zip ' );Открывает zip-архив из строки.
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> openFromString ( $ stringContents );Открывает zip-архив из потока.
$ stream = fopen ( ' file.zip ' , ' rb ' );
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> openFromStream ( $ stream );Возвращает количество записей в архиве.
$ zipFile = new PhpZip ZipFile ();
$ count = count ( $ zipFile );
// or
$ count = $ zipFile -> count ();Возвращает список файлов архива.
$ zipFile = new PhpZip ZipFile ();
$ listFiles = $ zipFile -> getListFiles ();
// example array contents:
// array (
// 0 => 'info.txt',
// 1 => 'path/to/file.jpg',
// 2 => 'another path/',
// 3 => '0',
// ) Возвращает содержимое записи, используя ее имя.
// $entryName = 'path/to/example-entry-name.txt';
$ zipFile = new PhpZip ZipFile ();
$ contents = $ zipFile [ $ entryName ];
// or
$ contents = $ zipFile -> getEntryContents ( $ entryName );Проверяет, есть ли запись в архиве.
// $entryName = 'path/to/example-entry-name.txt';
$ zipFile = new PhpZip ZipFile ();
$ hasEntry = isset ( $ zipFile [ $ entryName ]);
// or
$ hasEntry = $ zipFile -> hasEntry ( $ entryName );Проверяет, что запись в архиве является каталогом.
// $entryName = 'path/to/';
$ zipFile = new PhpZip ZipFile ();
$ isDirectory = $ zipFile -> isDirectory ( $ entryName );Извлеките содержимое архива. Каталог должен существовать.
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> extractTo ( $ directory );Извлеките несколько файлов в каталог. Каталог должен существовать.
// $toDirectory = '/tmp';
$ extractOnlyFiles = [
' filename1 ' ,
' filename2 ' ,
' dir/dir/dir/ '
];
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> extractTo ( $ toDirectory , $ extractOnlyFiles ); ZipFile — это итератор. Может перебирать все записи в цикле foreach .
foreach ( $ zipFile as $ entryName => $ contents ){
echo " Filename: $ entryName " . PHP_EOL ;
echo " Contents: $ contents " . PHP_EOL ;
echo ' ----------------------------- ' . PHP_EOL ;
} Может перебирать 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 ();
}Возвращает комментарий к ZIP-архиву.
$ zipFile = new PhpZip ZipFile ();
$ commentArchive = $ zipFile -> getArchiveComment ();Возвращает комментарий к записи, используя имя записи.
$ zipFile = new PhpZip ZipFile ();
$ commentEntry = $ zipFile -> getEntryComment ( $ entryName );Все способы добавления записей в ZIP-архив позволяют указать метод сжатия содержимого.
Доступны следующие методы сжатия:
PhpZipConstantsZipCompressionMethod::STORED — без сжатияPhpZipConstantsZipCompressionMethod::DEFLATED — выключить сжатиеPhpZipConstantsZipCompressionMethod::BZIP2 — сжатие Bzip2 с расширением ext-bz2 Добавляет файл в ZIP-архив по заданному пути.
$ 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 Добавляет SplFileInfo в ZIP-архив.
// $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 ,
]); Добавляет файлы из SymfonyComponentFinderFinder в ZIP-архив.
$ finder = new Symfony Component Finder Finder ();
$ finder
-> files ()
-> name ( ' *.{jpg,jpeg,gif,png} ' )
-> name ( ' /^[0-9a-f]./ ' )
-> contains ( ' /lorems+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 ' )
]);Добавляет файл в ZIP-архив, используя его содержимое.
$ 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 Добавляет запись из потока в ZIP-архив.
$ 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 = new PhpZip ZipFile ();
// $path = "path/to/";
$ zipFile -> addEmptyDir ( $ path );
// or
$ zipFile [ $ path ] = null ;Добавляет все записи из массива.
$ 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 = 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 = 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 Добавляет файлы из итератора каталогов.
// $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Пример с игнорированием некоторых файлов:
$ ignoreFiles = [
' file_ignore.txt ' ,
' dir_ignore/sub dir ignore/ '
];
// $directoryIterator = new DirectoryIterator($dir); // without subdirectories
// $directoryIterator = new RecursiveDirectoryIterator($dir); // with subdirectories
// use PhpZipUtilIteratorIgnoreFilesFilterIterator for non-recursive search
$ zipFile = new PhpZip ZipFile ();
$ ignoreIterator = new PhpZip Util Iterator IgnoreFilesRecursiveFilterIterator (
$ directoryIterator ,
$ ignoreFiles
);
$ zipFile -> addFilesFromIterator ( $ ignoreIterator );Добавляет файлы из каталога по шаблону без подкаталогов.
$ 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 Добавляет файлы из каталога по шаблону glob с подкаталогами.
$ 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 Добавляет файлы из каталога по шаблону PCRE без подкаталогов.
$ 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 Добавляет файлы из каталога по шаблону PCRE с подкаталогами.
$ 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 Удаляет запись в архиве по ее имени.
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> deleteFromName ( $ entryName );Удаляет записи в архиве, используя шаблон glob.
$ globPattern = ' **.{jpg,jpeg,png,gif} ' ; // example glob pattern -> delete all .jpg, .jpeg, .png and .gif files
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> deleteFromGlob ( $ globPattern );Удаляет записи в архиве по шаблону PCRE.
$ regexPattern = ' /.(jpe?g|png|gif)$/si ' ; // example regex pattern -> delete all .jpg, .jpeg, .png and .gif files
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> deleteFromRegex ( $ regexPattern );Удаляет все записи в ZIP-архиве.
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> deleteAll ();Переименовывает запись, определенную ее именем.
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> rename ( $ oldName , $ newName );Установите уровень сжатия для всех файлов в архиве.
Обратите внимание, что этот метод не применяется к записям, добавленным после запуска этого метода.
По умолчанию уровень сжатия равен 5 ( PhpZipConstantsZipCompressionLevel::NORMAL ) или уровню сжатия, указанному в архиве для сжатия Deflate.
Поддерживаются значения в диапазоне от 1 ( PhpZipConstantsZipCompressionLevel::SUPER_FAST ) до 9 ( PhpZipConstantsZipCompressionLevel::MAXIMUM ). Чем выше число, тем лучше и дольше сжатие.
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> setCompressionLevel ( PhpZip Constants ZipCompressionLevel:: MAXIMUM );Устанавливает уровень сжатия записи по ее имени.
Поддерживаются значения в диапазоне от 1 ( PhpZipConstantsZipCompressionLevel::SUPER_FAST ) до 9 ( PhpZipConstantsZipCompressionLevel::MAXIMUM ). Чем выше число, тем лучше и дольше сжатие.
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> setCompressionLevelEntry ( $ entryName , PhpZip Constants ZipCompressionLevel:: FAST );Устанавливает метод сжатия записи по ее имени.
Доступны следующие методы сжатия:
PhpZipConstantsZipCompressionMethod::STORED — без сжатияPhpZipConstantsZipCompressionMethod::DEFLATED — выключить сжатиеPhpZipConstantsZipCompressionMethod::BZIP2 — сжатие Bzip2 с расширением ext-bz2 $ zipFile = new PhpZip ZipFile ();
$ zipFile -> setCompressionMethodEntry ( $ entryName , PhpZip Constants ZipCompressionMethod:: DEFLATED );Установите комментарий ZIP-архива.
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> setArchiveComment ( $ commentArchive );Установите комментарий к записи, определяемый ее именем.
$ zipFile = new PhpZip ZipFile ();
$ zipFile -> setEntryComment ( $ entryName , $ comment );Выбор записей в архиве для выполнения над ними операций.
$ zipFile = new PhpZip ZipFile ();
$ matcher = $ zipFile -> matcher ();Выбор файлов из архива по одному:
$ matcher
-> add ( ' entry name ' )
-> add ( ' another entry ' );Выберите несколько файлов в архиве:
$ matcher -> add ([
' entry name ' ,
' another entry name ' ,
' path/ '
]);Выбор файлов по регулярному выражению:
$ matcher -> match ( ' ~.jpe?g$~i ' );Выбрать все файлы в архиве:
$ matcher -> all ();count() — получает количество выбранных записей:
$ count = count ( $ matcher );
// or
$ count = $ matcher -> count ();getMatches() — возвращает список выбранных записей:
$ entries = $ matcher -> getMatches ();
// example array contents: ['entry name', 'another entry name'];вызвать() — вызвать вызываемую функцию для выбранных записей:
// example
$ matcher -> invoke ( static function ( $ entryName ) use ( $ zipFile ) {
$ newName = preg_replace ( ' ~.(jpe?g)$~i ' , ' .no_optimize.$1 ' , $ entryName );
$ zipFile -> rename ( $ entryName , $ newName );
});Функции для работы с выбранными записями:
$ 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 Реализована поддержка методов шифрования:
PhpZipConstantsZipEncryptionMethod::PKWARE — традиционное шифрование PKWARE (устаревшее)PhpZipConstantsZipEncryptionMethod::WINZIP_AES_256 — 256-битное шифрование WinZip AES (рекомендуется)PhpZipConstantsZipEncryptionMethod::WINZIP_AES_192 — 192-битное шифрование WinZip AES.PhpZipConstantsZipEncryptionMethod::WINZIP_AES_128 — 128-битное шифрование WinZip AES. Установите пароль для открытого архива.
Установка пароля не требуется для добавления новых записей или удаления существующих, но если вы хотите извлечь контент или изменить метод/уровень сжатия, метод шифрования или сменить пароль, в этом случае пароль необходимо указать.
$ zipFile -> setReadPassword ( $ password );Получает пароль для чтения записи, определенной ее именем.
$ zipFile -> setReadPasswordEntry ( $ entryName , $ password );Устанавливает новый пароль для всех файлов в архиве.
Обратите внимание, что этот метод не применяется к записям, добавленным после запуска этого метода.
$ zipFile -> setPassword ( $ password );Вы можете установить метод шифрования:
$ encryptionMethod = PhpZip Constants ZipEncryptionMethod:: WINZIP_AES_256 ;
$ zipFile -> setPassword ( $ password , $ encryptionMethod );Устанавливает новый пароль для записи, определяемой ее именем.
$ zipFile -> setPasswordEntry ( $ entryName , $ password );Вы можете установить метод шифрования:
$ encryptionMethod = PhpZip Constants ZipEncryptionMethod:: WINZIP_AES_256 ;
$ zipFile -> setPasswordEntry ( $ entryName , $ password , $ encryptionMethod );Отключите шифрование для всех записей, которые уже есть в архиве.
Обратите внимание, что этот метод не применяется к записям, добавленным после запуска этого метода.
$ zipFile -> disableEncryption ();Отключить шифрование записи, определяемой ее именем.
$ zipFile -> disableEncryptionEntry ( $ entryName );Отменить все изменения, сделанные в архиве.
$ zipFile -> unchangeAll ();Отменить изменения в архивном комментарии.
$ zipFile -> unchangeArchiveComment ();Отменить изменения записи, определенной ее именем.
$ zipFile -> unchangeEntry ( $ entryName );Сохраняет архив в файл.
$ zipFile -> saveAsFile ( $ filename );Записывает архив в поток.
// $fp = fopen($filename, 'w+b');
$ zipFile -> saveAsStream ( $ fp );Выводит ZIP-архив в виде строки.
$ rawZipArchiveBytes = $ zipFile -> outputAsString ();Выводит ZIP-архив в браузер.
$ zipFile -> outputAsAttachment ( $ outputFilename );Вы можете установить Mime-Type:
$ mimeType = ' application/zip ' ;
$ zipFile -> outputAsAttachment ( $ outputFilename , $ mimeType );Выводит ZIP-архив как ответ PSR-7.
Метод вывода можно использовать в любой платформе, совместимой с PSR-7.
// $response = ....; // instance PsrHttpMessageResponseInterface
$ zipFile -> outputAsPsr7Response ( $ response , $ outputFilename );Вы можете установить Mime-Type:
$ mimeType = ' application/zip ' ;
$ zipFile -> outputAsPsr7Response ( $ response , $ outputFilename , $ mimeType );Выводит ZIP-архив как ответ Symfony.
Метод вывода можно использовать в среде Symfony.
$ response = $ zipFile -> outputAsSymfonyResponse ( $ outputFilename );Вы можете установить Mime-Type:
$ mimeType = ' application/zip ' ;
$ response = $ zipFile -> outputAsSymfonyResponse ( $ outputFilename , $ mimeType );Пример использования в 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 PhpZipExceptionZipException
*/
public function __invoke ( string $ id ): Response
{
$ zipFile = new ZipFile ();
$ zipFile [ ' file ' ] = ' contents ' ;
$ outputFilename = $ id . ' .zip ' ;
return $ zipFile -> outputAsSymfonyResponse ( $ outputFilename );
}
}Сохраните изменения и заново откройте измененный архив.
$ zipFile -> rewrite ();Закройте архив.
$ zipFile -> close ();Установите зависимости для разработки:
composer install --devЗапустите тесты:
vendor/bin/phpunitИзменения документированы на странице релизов.
Обновите основную версию файла composer.json до ^4.0 .
{
"require" : {
"nelexa/zip" : " ^4.0 "
}
} Затем установите обновления с помощью Composer :
composer update nelexa/zipОбновите свой код для работы с новой версией: BC.
zipalign . Эта функциональность будет помещена в отдельный пакет nelexa/apkfile . Обновите основную версию файла composer.json до ^3.0 .
{
"require" : {
"nelexa/zip" : " ^3.0 "
}
} Затем установите обновления с помощью Composer :
composer update nelexa/zipОбновите свой код для работы с новой версией:
ZipOutputFile объединен с ZipFile и удален.new PhpZipZipOutputFile() в new PhpZipZipFile()PhpZipZipFile::openFromFile($filename); to (new PhpZipZipFile())->openFile($filename);PhpZipZipOutputFile::openFromFile($filename); to (new PhpZipZipFile())->openFile($filename);PhpZipZipFile::openFromString($contents); to (new PhpZipZipFile())->openFromString($contents);PhpZipZipFile::openFromStream($stream); to (new PhpZipZipFile())->openFromStream($stream);PhpZipZipOutputFile::create() в new PhpZipZipFile()PhpZipZipOutputFile::openFromZipFile(PhpZipZipFile $zipFile) > (new PhpZipZipFile())->openFile($filename);addFromFile в addFilesetLevel для setCompressionLevelZipFile::setPassword в ZipFile::withReadPasswordZipOutputFile::setPassword в ZipFile::withNewPasswordZipOutputFile::disableEncryptionAllEntries в ZipFile::withoutPasswordZipOutputFile::setComment в ZipFile::setArchiveCommentZipFile::getComment в ZipFile::getArchiveCommentaddDir , addFilesFromGlob , addFilesFromRegex .getLevelsetCompressionMethodsetEntryPassword