Skip to content
PhpZip is a php-library for extended work with ZIP-archives.
Branch: master
Clone or download
Ne-Lexa Merge pull request #36 from chrisgraham/develop
Fixed slightly confusing language regarding setPassword
Latest commit 97db60a Apr 4, 2019

README.md

PhpZip

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

Build Status Latest Stable Version Total Downloads Minimum PHP Version License

Russian Documentation

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).
  • Built-in support for aligning the archive to optimize Android packages (APK) zipalign.
  • Working with passwords for PHP 5.5

    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 >= 5.5 (preferably 64-bit).
  • Optional php-extension bzip2 for BZIP2 compression.
  • Optional php-extension openssl or mcrypt 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.

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

ZipFile::getListFiles - returns list of archive files.

$listFiles = $zipFile->getListFiles();

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

ZipFile::getEntryContent - returns the entry contents using its name.

// $entryName = 'path/to/example-entry-name.txt';

$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';

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

ZipFile::isDirectory - checks that the entry in the archive is a directory.

// $entryName = 'path/to/';

$isDirectory = $zipFile->isDirectory($entryName);

ZipFile::extractTo - extract the archive contents. The directory must exist.

$zipFile->extractTo($directory);

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

$extractOnlyFiles = [
    "filename1", 
    "filename2", 
    "dir/dir/dir/"
];
$zipFile->extractTo($directory, $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.

$commentArchive = $zipFile->getArchiveComment();

ZipFile::getEntryComment - returns the comment of an entry using the entry name.

$commentEntry = $zipFile->getEntryComment($entryName);

ZipFile::getEntryInfo - returns detailed information about the entry in the archive

$zipInfo = $zipFile->getEntryInfo('file.txt');

$arrayInfo = $zipInfo->toArray();
// example array contents:
// array (
//   'name' => 'file.gif',
//   'folder' => false,
//   'size' => '43',
//   'compressed_size' => '43',
//   'modified' => 1510489440,
//   'created' => null,
//   'accessed' => null,
//   'attributes' => '-rw-r--r--',
//   'encrypted' => false,
//   'encryption_method' => 0,
//   'comment' => '',
//   'crc' => 782934147,
//   'method_name' => 'No compression',
//   'compression_method' => 0,
//   'platform' => 'UNIX',
//   'version' => 10,
// )

print_r($zipInfo);
// output:
//PhpZip\Model\ZipInfo Object
//(
//    [name:PhpZip\Model\ZipInfo:private] => file.gif
//    [folder:PhpZip\Model\ZipInfo:private] => 
//    [size:PhpZip\Model\ZipInfo:private] => 43
//    [compressedSize:PhpZip\Model\ZipInfo:private] => 43
//    [mtime:PhpZip\Model\ZipInfo:private] => 1510489324
//    [ctime:PhpZip\Model\ZipInfo:private] => 
//    [atime:PhpZip\Model\ZipInfo:private] => 
//    [encrypted:PhpZip\Model\ZipInfo:private] => 
//    [comment:PhpZip\Model\ZipInfo:private] => 
//    [crc:PhpZip\Model\ZipInfo:private] => 782934147
//    [methodName:PhpZip\Model\ZipInfo:private] => No compression
//    [compressionMethod:PhpZip\Model\ZipInfo:private] => 0
//    [platform:PhpZip\Model\ZipInfo:private] => UNIX
//    [version:PhpZip\Model\ZipInfo:private] => 10
//    [attributes:PhpZip\Model\ZipInfo:private] => -rw-r--r--
//    [encryptionMethod:PhpZip\Model\ZipInfo:private] => 0
//    [compressionLevel:PhpZip\Model\ZipInfo:private] => -1
//)

echo $zipInfo;
// Output:
// PhpZip\Model\ZipInfo {Name="file.gif", Size="43 bytes", Compressed size="43 bytes", Modified time="2017-11-12T15:22:04+03:00", Crc=0x2eaaa083, Method name="No compression", Attributes="-rw-r--r--", Platform="UNIX", Version=10}

ZipFile::getAllInfo - returns detailed information about all entries in the archive.

$zipAllInfo = $zipFile->getAllInfo();

print_r($zipAllInfo);
//Array
//(
//    [file.txt] => PhpZip\Model\ZipInfo Object
//    (
//            ...
//    )
//
//    [file2.txt] => PhpZip\Model\ZipInfo Object
//    (
//            ...
//    )
//    
//    ...
//)

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\ZipFile::METHOD_STORED - no compression
  • \PhpZip\ZipFile::METHOD_DEFLATED - Deflate compression
  • \PhpZip\ZipFile::METHOD_BZIP2 - Bzip2 compression with the extension ext-bz2

ZipFile::addFile - adds a file to a ZIP archive from the given path.

// $file = '...../file.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);
// or
$zipFile[$entryName] = new \SplFileInfo($file);

// you can specify a compression method
$zipFile->addFile($file, $entryName, ZipFile::METHOD_STORED); // No compression
$zipFile->addFile($file, $entryName, ZipFile::METHOD_DEFLATED); // Deflate compression
$zipFile->addFile($file, $entryName, ZipFile::METHOD_BZIP2); // BZIP2 compression

ZipFile::addFromString - adds a file to a ZIP archive using its contents.

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

// you can specify a compression method
$zipFile->addFromString($entryName, $contents, ZipFile::METHOD_STORED); // No compression
$zipFile->addFromString($entryName, $contents, ZipFile::METHOD_DEFLATED); // Deflate compression
$zipFile->addFromString($entryName, $contents, ZipFile::METHOD_BZIP2); // BZIP2 compression

ZipFile::addFromStream - adds a entry from the stream to the ZIP archive.

// $stream = fopen(..., 'rb');

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

// you can specify a compression method
$zipFile->addFromStream($stream, $entryName, ZipFile::METHOD_STORED); // No compression
$zipFile->addFromStream($stream, $entryName, ZipFile::METHOD_DEFLATED); // Deflate compression
$zipFile->addFromStream($stream, $entryName, ZipFile::METHOD_BZIP2); // BZIP2 compression

ZipFile::addEmptyDir - add a new directory.

// $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', 'r'), // add an entry from the stream
    'path/to/file.dat' => new \SplFileInfo('..../filename'), // add an entry from the file
];

$zipFile->addAll($entries);

ZipFile::addDir - adds files to the archive from the directory on the specified path without subdirectories.

$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, ZipFile::METHOD_STORED); // No compression
$zipFile->addDir($dirName, $localPath, ZipFile::METHOD_DEFLATED); // Deflate compression
$zipFile->addDir($dirName, $localPath, ZipFile::METHOD_BZIP2); // BZIP2 compression

ZipFile::addDirRecursive - adds files to the archive from the directory on the specified path with subdirectories.

$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, ZipFile::METHOD_STORED); // No compression
$zipFile->addDirRecursive($dirName, $localPath, ZipFile::METHOD_DEFLATED); // Deflate compression
$zipFile->addDirRecursive($dirName, $localPath, ZipFile::METHOD_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->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, ZipFile::METHOD_STORED); // No compression
$zipFile->addFilesFromIterator($directoryIterator, $localPath, ZipFile::METHOD_DEFLATED); // Deflate compression
$zipFile->addFilesFromIterator($directoryIterator, $localPath, ZipFile::METHOD_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
$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->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, ZipFile::METHOD_STORED); // No compression
$zipFile->addFilesFromGlob($dir, $globPattern, $localPath, ZipFile::METHOD_DEFLATED); // Deflate compression
$zipFile->addFilesFromGlob($dir, $globPattern, $localPath, ZipFile::METHOD_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->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, ZipFile::METHOD_STORED); // No compression
$zipFile->addFilesFromGlobRecursive($dir, $globPattern, $localPath, ZipFile::METHOD_DEFLATED); // Deflate compression
$zipFile->addFilesFromGlobRecursive($dir, $globPattern, $localPath, ZipFile::METHOD_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->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, ZipFile::METHOD_STORED); // No compression
$zipFile->addFilesFromRegex($dir, $regexPattern, $localPath, ZipFile::METHOD_DEFLATED); // Deflate compression
$zipFile->addFilesFromRegex($dir, $regexPattern, $localPath, ZipFile::METHOD_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, ZipFile::METHOD_STORED); // No compression
$zipFile->addFilesFromRegexRecursive($dir, $regexPattern, $localPath, ZipFile::METHOD_DEFLATED); // Deflate compression
$zipFile->addFilesFromRegexRecursive($dir, $regexPattern, $localPath, ZipFile::METHOD_BZIP2); // BZIP2 compression

Deleting entries from the archive

ZipFile::deleteFromName - deletes an entry in the archive using its name.

$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->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->deleteFromRegex($regexPattern);

ZipFile::deleteAll - deletes all entries in the ZIP archive.

$zipFile->deleteAll();

Working with entries and archive

ZipFile::rename - renames an entry defined by its name.

$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 -1 (\PhpZip\ZipFile::LEVEL_DEFAULT_COMPRESSION) or the compression level specified in the archive for Deflate compression.

The values -1 (\PhpZip\ZipFile::LEVEL_DEFAULT_COMPRESSION) and the range from 1 (\PhpZip\ZipFile::LEVEL_BEST_SPEED) to 9 (\PhpZip\ZipFile::LEVEL_BEST_COMPRESSION) are supported. The higher the number, the better and longer the compression.

$zipFile->setCompressionLevel(\PhpZip\ZipFile::LEVEL_BEST_COMPRESSION);

ZipFile::setCompressionLevelEntry - sets the compression level for the entry by its name.

The values -1 (\PhpZip\ZipFile::LEVEL_DEFAULT_COMPRESSION) and the range from 1 (\PhpZip\ZipFile::LEVEL_BEST_SPEED) to 9 (\PhpZip\ZipFile::LEVEL_BEST_COMPRESSION) are supported. The higher the number, the better and longer the compression.

$zipFile->setCompressionLevelEntry($entryName, \PhpZip\ZipFile::LEVEL_BEST_COMPRESSION);

ZipFile::setCompressionMethodEntry - sets the compression method for the entry by its name.

The following compression methods are available:

  • \PhpZip\ZipFile::METHOD_STORED - No compression
  • \PhpZip\ZipFile::METHOD_DEFLATED - Deflate compression
  • \PhpZip\ZipFile::METHOD_BZIP2 - Bzip2 compression with the extension ext-bz2
$zipFile->setCompressionMethodEntry($entryName, ZipFile::METHOD_DEFLATED);

ZipFile::setArchiveComment - set the comment of a ZIP archive.

$zipFile->setArchiveComment($commentArchive);

ZipFile::setEntryComment - set the comment of an entry defined by its name.

$zipFile->setEntryComment($entryName, $comment);

ZipFile::matcher - selecting entries in the archive to perform operations on them.

$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(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\ZipFile::ENCRYPTION_METHOD_TRADITIONAL - Traditional PKWARE encryption
  • \PhpZip\ZipFile::ENCRYPTION_METHOD_WINZIP_AES_256 - WinZip AES encryption 256 bit (recommended)
  • \PhpZip\ZipFile::ENCRYPTION_METHOD_WINZIP_AES_192 - WinZip AES encryption 192 bit
  • \PhpZip\ZipFile::ENCRYPTION_METHOD_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 = ZipFile::ENCRYPTION_METHOD_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 = ZipFile::ENCRYPTION_METHOD_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);

zipalign

ZipFile::setZipAlign - sets the alignment of the archive to optimize APK files (Android packages).

This method adds padding to unencrypted and not compressed entries, to optimize memory consumption in the Android system. It is recommended to use for APK files. The file may grow slightly.

This method is an alternative to executing the zipalign -f -v 4 filename.zip.

More details can be found on the link.

$zipFile->setZipAlign(4);

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::outputAsResponse - 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->outputAsResponse($response, $outputFilename);

You can set the Mime-Type:

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

An example for the Slim Framework:

$app = new \Slim\App;
$app->get('/download', function ($req, $res, $args) {
    $zipFile = new \PhpZip\ZipFile();
    $zipFile['file.txt'] = 'content';
    return $zipFile->outputAsResponse($res, 'file.zip');
});
$app->run();

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 -v -c phpunit.xml

Changelog

Link to Changelog

Upgrade

Upgrade version 2 to version 3.0

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
You can’t perform that action at this time.