1
0
mirror of https://github.com/Ne-Lexa/php-zip.git synced 2025-08-31 10:41:50 +02:00

Completely rewritten code.

Implement read-only zip file - class \PhpZip\ZipFile, create and update zip file - \PhpZip\ZipOutputFile.
Supports ZIP64 ext, Traditional PKWARE Encryption, WinZip AES Encryption.
This commit is contained in:
Ne-Lexa
2016-09-26 12:04:38 +03:00
parent 5c23e588ff
commit 560a94c910
48 changed files with 7785 additions and 2905 deletions

550
README.md
View File

@@ -1,249 +1,455 @@
## Documentation
`PhpZip` Version 2
================
`PhpZip` - is to create, update, opening and unpacking ZIP archives in pure PHP.
Create and manipulate zip archives. No use ZipArchive class and php-zip extension.
The library supports `ZIP64`, `Traditional PKWARE Encryption` and `WinZIP AES Encryption`.
### class \Nelexa\Zip\ZipFile
Initialization
The library does not require extension `php-xml` and class `ZipArchive`.
Requirements
------------
- `PHP` >= 5.4 (64 bit)
- Php-extension `mbstring`
- Optional php-extension `bzip2` for BZIP2 compression.
- Optional php-extension `openssl` or `mcrypt` for `WinZip Aes Encryption` support.
Installation
------------
`composer require nelexa/zip`
Documentation
-------------
#### Class `\PhpZip\ZipFile` (open, extract, info)
Open zip archive from file.
```php
$zip = new \Nelexa\Zip\ZipFile();
$zipFile = \PhpZip\ZipFile::openFromFile($filename);
```
Create archive
Open zip archive from data string.
```php
$zip->create();
$data = file_get_contents($filename);
$zipFile = \PhpZip\ZipFile::openFromString($data);
```
Open archive file
Open zip archive from stream resource.
```php
$zip->open($filename);
$stream = fopen($filename, 'rb');
$zipFile = \PhpZip\ZipFile::openFromStream($stream);
```
Open archive from string
Get num entries.
```php
$zip->openFromString($string)
$count = $zipFile->count();
// or
$count = count($zipFile);
```
Set password
Get list files.
```php
$zip->setPassword($password);
$listFiles = $zipFile->getListFiles();
```
List files
Foreach zip entries.
```php
$listFiles = $zip->getListFiles();
foreach($zipFile as $entryName => $dataContent){
echo "Entry: $entryName" . PHP_EOL;
echo "Data: $dataContent" . PHP_EOL;
echo "-----------------------------" . PHP_EOL;
}
```
Get count files
Iterator zip entries.
```php
$countFiles = $zip->getCountFiles();
$iterator = new \ArrayIterator($zipFile);
while ($iterator->valid())
{
$entryName = $iterator->key();
$dataContent = $iterator->current();
echo "Entry: $entryName" . PHP_EOL;
echo "Data: $dataContent" . PHP_EOL;
echo "-----------------------------" . PHP_EOL;
$iterator->next();
}
```
Checks whether a entry exists.
```php
$boolValue = $zipFile->hasEntry($entryName);
```
Check whether the directory entry.
```php
$boolValue = $zipFile->isDirectory($entryName);
```
Set password to all encrypted entries.
```php
$zipFile->setPassword($password);
```
Set password to concrete zip entry.
```php
$zipFile->setEntryPassword($entryName, $password);
```
Get comment archive.
```php
$commentArchive = $zipFile->getComment();
```
Get comment zip entry.
```php
$commentEntry = $zipFile->getEntryComment($entryName);
```
Get entry info.
```php
$zipInfo = $zipFile->getEntryInfo('file.txt');
echo $zipInfo . PHP_EOL;
// ZipInfo {Path="file.txt", Size=9.77KB, Compressed size=2.04KB, Modified time=2016-09-24T19:25:10+03:00, Crc=0x4b5ab5c7, Method="Deflate", Platform="UNIX", Version=20}
print_r($zipInfo);
//PhpZip\Model\ZipInfo Object
//(
// [path:PhpZip\Model\ZipInfo:private] => file.txt
// [folder:PhpZip\Model\ZipInfo:private] =>
// [size:PhpZip\Model\ZipInfo:private] => 10000
// [compressedSize:PhpZip\Model\ZipInfo:private] => 2086
// [mtime:PhpZip\Model\ZipInfo:private] => 1474734310
// [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] => 1264235975
// [method:PhpZip\Model\ZipInfo:private] => Deflate
// [platform:PhpZip\Model\ZipInfo:private] => UNIX
// [version:PhpZip\Model\ZipInfo:private] => 20
//)
```
Get info for all entries.
```php
$zipAllInfo = $zipFile->getAllInfo();
print_r($zipAllInfo);
//Array
//(
// [file.txt] => PhpZip\Model\ZipInfo Object
// (
// ...
// )
//
// [file2.txt] => PhpZip\Model\ZipInfo Object
// (
// ...
// )
//
// ...
//)
```
Extract all files to directory.
```php
$zipFile->extractTo($directory);
```
Extract some files to directory.
```php
$extractOnlyFiles = ["filename1", "filename2", "dir/dir/dir/"];
$zipFile->extractTo($directory, $extractOnlyFiles);
```
Get entry content.
```php
$data = $zipFile->getEntryContent($entryName);
```
Close zip archive.
```php
$zipFile->close();
```
#### Class `\PhpZip\ZipOutputFile` (create, update, extract)
Create zip archive.
```php
$zipOutputFile = new \PhpZip\ZipOutputFile();
// or
$zipOutputFile = \PhpZip\ZipOutputFile::create();
```
Open zip file from update.
```php
// initial ZipFile
$zipFile = \PhpZip\ZipFile::openFromFile($filename);
// Create output stream from update zip file
$zipOutputFile = new \PhpZip\ZipOutputFile($zipFile);
// or
$zipOutputFile = \PhpZip\ZipOutputFile::openFromZipFile($zipFile);
```
Add entry from file.
```php
$zipOutputFile->addFromFile($filename); // $entryName == basename($filename);
$zipOutputFile->addFromFile($filename, $entryName);
$zipOutputFile->addFromFile($filename, $entryName, ZipEntry::METHOD_DEFLATED);
$zipOutputFile->addFromFile($filename, null, ZipEntry::METHOD_BZIP2); // $entryName == basename($filename);
```
Add entry from string data.
```php
$zipOutputFile->addFromString($entryName, $data)
$zipOutputFile->addFromString($entryName, $data, ZipEntry::METHOD_DEFLATED)
```
Add entry from stream.
```php
$zipOutputFile->addFromStream($stream, $entryName)
$zipOutputFile->addFromStream($stream, $entryName, ZipEntry::METHOD_DEFLATED)
```
Add empty dir
```php
$zip->addEmptyDir($dirName);
$zipOutputFile->addEmptyDir($dirName);
```
Add dir
Add a directory **recursively** to the archive.
```php
$directory = "/tmp";
$ignoreFiles = array("xxx.file", "xxx2.file");
$zip->addDir($directory); // add path /tmp to /
$zip->addDir($directory, "var/temp"); // add path /tmp to var/temp
$zip->addDir($directory, "var/temp", $ignoreFiles); // add path /tmp to var/temp and ignore files xxx.file and xxx2.file
$zipOutputFile->addDir($dirName);
// or
$zipOutputFile->addDir($dirName, true);
```
Add files from glob pattern
Add a directory **not recursively** to the archive.
```php
$zip->addGlob("music/*.mp3"); // add all mp3 files
$zipOutputFile->addDir($dirName, false);
```
Add files from regex pattern
Add a directory to the archive by path `$moveToPath`
```php
$zip->addPattern("~file[0-9]+\.jpg$~", "picture/");
$moveToPath = 'dir/subdir/';
$zipOutputFile->addDir($dirName, $boolResursive, $moveToPath);
```
Add file
Add a directory to the archive with ignoring files.
```php
$zip->addFile($filename);
$zip->addFile($filename, $localName);
$zip->addFile($filename, $localName, \Nelexa\Zip\ZipEntry::COMPRESS_METHOD_STORED); // no compression
$zip->addFile($filename, $localName, \Nelexa\Zip\ZipEntry::COMPRESS_METHOD_DEFLATED);
$ignoreFiles = ["file_ignore.txt", "dir_ignore/sub dir ignore/"];
$zipOutputFile->addDir($dirName, $boolResursive, $moveToPath, $ignoreFiles);
```
Add file from string
Add a directory and set compression method.
```php
$zip->addFromString($localName, $contents);
$zip->addFromString($localName, $contents, \Nelexa\Zip\ZipEntry::COMPRESS_METHOD_STORED); // no compression
$zip->addFromString($localName, $contents, \Nelexa\Zip\ZipEntry::COMPRESS_METHOD_DEFLATED);
$compressionMethod = ZipEntry::METHOD_DEFLATED;
$zipOutputFile->addDir($dirName, $boolRecursive, $moveToPath, $ignoreFiles, $compressionMethod);
```
Update timestamp for all files
Add a files **recursively** from [glob pattern](https://en.wikipedia.org/wiki/Glob_(programming)) to the archive.
```php
$timestamp = time(); // now time
$zip->updateTimestamp($timestamp);
$globPattern = '**.{jpg,jpeg,png,gif}'; // example glob pattern -> add all .jpg, .jpeg, .png and .gif files
$zipOutputFile->addFilesFromGlob($inputDir, $globPattern);
```
Delete files from glob pattern
Add a files **not recursively** from [glob pattern](https://en.wikipedia.org/wiki/Glob_(programming)) to the archive.
```php
$zip->deleteGlob("*.jpg"); // remove all jpg files
$recursive = false;
$zipOutputFile->addFilesFromGlob($inputDir, $globPattern, $recursive);
```
Delete files from regex pattern
Add a files from [glob pattern](https://en.wikipedia.org/wiki/Glob_(programming)) to the archive by path `$moveToPath`.
```php
$zip->deletePattern("~\.jpg$~i"); // remove all jpg files
$moveToPath = 'dir/dir2/dir3';
$zipOutputFile->addFilesFromGlob($inputDir, $globPattern, $recursive = true, $moveToPath);
```
Delete file from index
Add a files from [glob pattern](https://en.wikipedia.org/wiki/Glob_(programming)) to the archive and set compression method.
```php
$zip->deleteIndex(0);
$compressionMethod = ZipEntry::METHOD_DEFLATED;
$zipOutputFile->addFilesFromGlob($inputDir, $globPattern, $recursive, $moveToPath, $compressionMethod);
```
Delete all files
Add a files **recursively** from [RegEx (Regular Expression) pattern](https://en.wikipedia.org/wiki/Regular_expression) to the archive.
```php
$zip->deleteAll();
$regexPattern = '/\.(jpe?g|png|gif)$/si'; // example regex pattern -> add all .jpg, .jpeg, .png and .gif files
$zipOutputFile->addFilesFromRegex($inputDir, $regexPattern);
```
Delete from file name
Add a files **not recursively** from [RegEx (Regular Expression) pattern](https://en.wikipedia.org/wiki/Regular_expression) to the archive.
```php
$zip->deleteName($filename);
$recursive = false;
$zipOutputFile->addFilesFromRegex($inputDir, $regexPattern, $recursive);
```
Extract zip archive
Add a files from [RegEx (Regular Expression) pattern](https://en.wikipedia.org/wiki/Regular_expression) to the archive by path `$moveToPath`.
```php
$zip->extractTo($toPath)
$zip->extractTo($toPath, array("file1", "file2")); // extract only files file1 and file2
$moveToPath = 'dir/dir2/dir3';
$zipOutputFile->addFilesFromRegex($inputDir, $regexPattern, $recursive = true, $moveToPath);
```
Get archive comment
Add a files from [RegEx (Regular Expression) pattern](https://en.wikipedia.org/wiki/Regular_expression) to the archive and set compression method.
```php
$archiveComment = $zip->getArchiveComment();
$compressionMethod = ZipEntry::METHOD_DEFLATED;
$zipOutputFile->addFilesFromRegex($inputDir, $regexPattern, $recursive, $moveToPath, $compressionMethod);
```
Set archive comment
Rename entry name.
```php
$zip->setArchiveComment($comment)
$zipOutputFile->rename($oldName, $newName);
```
Get comment file from index
Delete entry by name.
```php
$commentFile = $zip->getCommentIndex($index);
$zipOutputFile->deleteFromName($entryName);
```
Set comment file from index
Delete entries from [glob pattern](https://en.wikipedia.org/wiki/Glob_(programming)).
```php
$zip->setCommentIndex($index, $comment);
$globPattern = '**.{jpg,jpeg,png,gif}'; // example glob pattern -> delete all .jpg, .jpeg, .png and .gif files
$zipOutputFile->deleteFromGlob($globPattern);
```
Get comment file from filename
Delete entries from [RegEx (Regular Expression) pattern](https://en.wikipedia.org/wiki/Regular_expression).
```php
$commentFile = $zip->getCommentName($filename);
$regexPattern = '/\.(jpe?g|png|gif)$/si'; // example regex pattern -> delete all .jpg, .jpeg, .png and .gif files
$zipOutputFile->deleteFromRegex($regexPattern);
```
Set comment file from filename
Delete all entries.
```php
$zip->setCommentName($name, $comment);
$zipOutputFile->deleteAll();
```
Get file content from index
Get num entries.
```php
$content = $zip->getFromIndex($index);
$count = $zipOutputFile->count();
// or
$count = count($zipOutputFile);
```
Get file content from filename
Get list files.
```php
$content = $zip->getFromName($name);
$listFiles = $zipOutputFile->getListFiles();
```
Get filename from index
Get the compression level for entries.
```php
$filename = $zip->getNameIndex($index);
$compressionLevel = $zipOutputFile->getLevel();
```
Rename file from index
Sets the compression level for entries.
```php
$zip->renameIndex($index, $newFilename);
// This property is only used if the effective compression method is DEFLATED or BZIP2.
// Legal values are ZipOutputFile::LEVEL_DEFAULT_COMPRESSION or range from
// ZipOutputFile::LEVEL_BEST_SPEED to ZipOutputFile::LEVEL_BEST_COMPRESSION.
$compressionMethod = ZipOutputFile::LEVEL_BEST_COMPRESSION;
$zipOutputFile->setLevel($compressionLevel);
```
Rename file from filename
Get comment archive.
```php
$zip->renameName($oldName, $newName);
$commentArchive = $zipOutputFile->getComment();
```
Get zip entries
Set comment archive.
```php
/**
* @var \Nelexa\Zip\ZipEntry[] $zipEntries
*/
$zipEntries = $zip->getZipEntries();
$zipOutputFile->setComment($commentArchive);
```
Get zip entry from index
Get comment zip entry.
```php
/**
* @var \Nelexa\Zip\ZipEntry $zipEntry
*/
$zipEntry = $zip->getZipEntryIndex($index);
$commentEntry = $zipOutputFile->getEntryComment($entryName);
```
Get zip entry from filename
Set comment zip entry.
```php
/**
* @var \Nelexa\Zip\ZipEntry $zipEntry
*/
$zipEntry = $zip->getZipEntryName($name);
$zipOutputFile->setEntryComment($entryName, $entryComment);
```
Get info from index
Set compression method for zip entry.
```php
$info = $zip->statIndex($index);
// [
// 'name' - filename
// 'index' - index number
// 'crc' - crc32
// 'size' - uncompressed size
// 'mtime' - last modify date time
// 'comp_size' - compressed size
// 'comp_method' - compressed method
// ]
```
Get info from name
```php
$info = $zip->statName($name);
// [
// 'name' - filename
// 'index' - index number
// 'crc' - crc32
// 'size' - uncompressed size
// 'mtime' - last modify date time
// 'comp_size' - compressed size
// 'comp_method' - compressed method
// ]
```
Get info from all files
```php
$info = $zip->getExtendedListFiles();
```
Get output contents
```php
$content = $zip->output();
```
Save opened file
```php
$isSuccessSave = $zip->save();
```
Save file as
```php
$zip->saveAs($outputFile);
```
Close archive
```php
$zip->close();
```
$compressionMethod = ZipEntry::METHOD_DEFLATED;
$zipOutputMethod->setCompressionMethod($entryName, $compressionMethod);
### Example create zip archive
```php
$zip = new \Nelexa\Zip\ZipFile();
$zip->create();
$zip->addFile("README.md");
$zip->addFile("README.md", "folder/README");
$zip->addFromString("folder/file.txt", "File content");
$zip->addEmptyDir("f/o/l/d/e/r");
$zip->setArchiveComment("Archive comment");
$zip->setCommentIndex(0, "Comment file with index 0");
$zip->saveAs("output.zip");
$zip->close();
// $ zipinfo output.zip
// Archive: output.zip
// Zip file size: 912 bytes, number of entries: 4
// -rw---- 1.0 fat 387 b- defN README.md
// -rw---- 1.0 fat 387 b- defN folder/README
// -rw---- 1.0 fat 12 b- defN folder/file.txt
// -rw---- 1.0 fat 0 b- stor f/o/l/d/e/r/
// 4 files, 786 bytes uncompressed, 448 bytes compressed: 43.0%
// Support compression methods:
// ZipEntry::METHOD_STORED - no compression
// ZipEntry::METHOD_DEFLATED - deflate compression
// ZipEntry::METHOD_BZIP2 - bzip2 compression (need bz2 extension)
```
### Example modification zip archive
Set a password for all previously added entries.
```php
$zip = new \Nelexa\Zip\ZipFile();
$zip->open("output.zip");
$zip->addFromString("new-file", file_get_contents(__FILE__));
$zip->saveAs("output2.zip");
$zip->close();
$zipOutputFile->setPassword($password);
```
Set a password and encryption method for all previously added entries.
```php
$encryptionMethod = ZipEntry::ENCRYPTION_METHOD_WINZIP_AES; // default value
$zipOutputFile->setPassword($password, $encryptionMethod);
// $ zipinfo output2.zip
// Archive: output2.zip
// Zip file size: 1331 bytes, number of entries: 5
// -rw---- 1.0 fat 387 b- defN README.md
// -rw---- 1.0 fat 387 b- defN folder/README
// -rw---- 1.0 fat 12 b- defN folder/file.txt
// -rw---- 1.0 fat 0 b- stor f/o/l/d/e/r/
// -rw---- 1.0 fat 593 b- defN new-file
// 5 files, 1379 bytes uncompressed, 775 bytes compressed: 43.8%
// Support encryption methods:
// ZipEntry::ENCRYPTION_METHOD_TRADITIONAL - Traditional PKWARE Encryption
// ZipEntry::ENCRYPTION_METHOD_WINZIP_AES - WinZip AES Encryption
```
Set a password for a concrete entry.
```php
$zipOutputFile->setEntryPassword($entryName, $password);
```
Set a password and encryption method for a concrete entry.
```php
$zipOutputFile->setEntryPassword($entryName, $password, $encryptionMethod);
// Support encryption methods:
// ZipEntry::ENCRYPTION_METHOD_TRADITIONAL - Traditional PKWARE Encryption
// ZipEntry::ENCRYPTION_METHOD_WINZIP_AES - WinZip AES Encryption (default value)
```
Remove password from all entries.
```php
$zipOutputFile->removePasswordAllEntries();
```
Remove password for concrete zip entry.
```php
$zipOutputFile->removePasswordFromEntry($entryName);
```
Save archive to a file.
```php
$zipOutputFile->saveAsFile($filename);
```
Save archive to a stream.
```php
$handle = fopen($filename, 'w+b);
$autoCloseResource = true;
$zipOutputFile->saveAsStream($handle, $autoCloseResource);
if(!$autoCloseResource){
fclose($handle);
}
```
Returns the zip archive as a string.
```php
$rawZipArchiveBytes = $zipOutputFile->outputAsString();
```
Output .ZIP archive as attachment and terminate.
```php
$zipOutputFile->outputAsAttachment($outputFilename);
// or set mime type
$zipOutputFile->outputAsAttachment($outputFilename = 'output.zip', $mimeType = 'application/zip');
```
Extract all files to directory.
```php
$zipOutputFile->extractTo($directory);
```
Extract some files to directory.
```php
$extractOnlyFiles = ["filename1", "filename2", "dir/dir/dir/"];
$zipOutputFile->extractTo($directory, $extractOnlyFiles);
```
Get entry contents.
```php
$data = $zipOutputFile->getEntryContent($entryName);
```
Foreach zip entries.
```php
foreach($zipOutputFile as $entryName => $dataContent){
echo "Entry: $entryName" . PHP_EOL;
echo "Data: $dataContent" . PHP_EOL;
echo "-----------------------------" . PHP_EOL;
}
```
Iterator zip entries.
```php
$iterator = new \ArrayIterator($zipOutputFile);
while ($iterator->valid())
{
$entryName = $iterator->key();
$dataContent = $iterator->current();
echo "Entry: $entryName" . PHP_EOL;
echo "Data: $dataContent" . PHP_EOL;
echo "-----------------------------" . PHP_EOL;
$iterator->next();
}
```
Close zip archive.
```php
$zipOutputFile->close();
```
Examples
--------
Create, open, extract and update archive.
```php
$outputFilename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'output.zip';
$outputDirExtract = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'extract';
if(!is_dir($outputDirExtract)){
mkdir($outputDirExtract, 0755, true);
}
$zipOutputFile = \PhpZip\ZipOutputFile::create(); // create archive
$zipOutputFile->addDir(__DIR__, true); // add this dir to archive
$zipOutputFile->saveAsFile($outputFilename); // save as file
$zipOutputFile->close(); // close output file, release all streams
$zipFile = \PhpZip\ZipFile::openFromFile($outputFilename); // open zip archive from file
$zipFile->extractTo($outputDirExtract); // extract files to dir
$zipOutputFile = \PhpZip\ZipOutputFile::openFromZipFile($zipFile); // create zip output archive for update
$zipOutputFile->deleteFromRegex('~^\.~'); // delete all hidden (Unix) files
$zipOutputFile->addFromString('dir/file.txt', 'Test file'); // add files from string contents
$zipOutputFile->saveAsFile($outputFilename); // update zip file
$zipOutputFile->close(); // close output file, release all streams
$zipFile->close(); // close input file, release all streams
```
Other examples can be found in the `tests/` folder
Running Tests
-------------
```bash
vendor/bin/phpunit -v --tap -c bootstrap.xml
```