Archive::Zip(3pm) | User Contributed Perl Documentation | Archive::Zip(3pm) |
Archive::Zip - Provide an interface to ZIP archive files.
# Create a Zip file use Archive::Zip qw( :ERROR_CODES :CONSTANTS ); my $zip = Archive::Zip->new(); # Add a directory my $dir_member = $zip->addDirectory( 'dirname/' ); # Add a file from a string with compression my $string_member = $zip->addString( 'This is a test', 'stringMember.txt' ); $string_member->desiredCompressionMethod( COMPRESSION_DEFLATED ); # Add a file from disk my $file_member = $zip->addFile( 'xyz.pl', 'AnotherName.pl' ); # Save the Zip file unless ( $zip->writeToFileNamed('someZip.zip') == AZ_OK ) { die 'write error'; } # Read a Zip file my $somezip = Archive::Zip->new(); unless ( $somezip->read( 'someZip.zip' ) == AZ_OK ) { die 'read error'; } # Change the compression type for a file in the Zip my $member = $somezip->memberNamed( 'stringMember.txt' ); $member->desiredCompressionMethod( COMPRESSION_STORED ); unless ( $zip->writeToFileNamed( 'someOtherZip.zip' ) == AZ_OK ) { die 'write error'; }
The Archive::Zip module allows a Perl program to create, manipulate, read, and write Zip archive files.
Zip archives can be created, or you can read from existing zip files.
Once created, they can be written to files, streams, or strings. Members can be added, removed, extracted, replaced, rearranged, and enumerated. They can also be renamed or have their dates, comments, or other attributes queried or modified. Their data can be compressed or uncompressed as needed.
Members can be created from members in existing Zip files, or from existing directories, files, or strings.
This module uses the Compress::Raw::Zlib library to read and write the compressed streams inside the files.
One can use Archive::Zip::MemberRead to read the zip file archive members as if they were files.
Regardless of what your local file system uses for file naming, names in a Zip file are in Unix format (forward slashes (/) separating directory names, etc.).
"Archive::Zip" tries to be consistent with file naming conventions, and will translate back and forth between native and Zip file names.
However, it can't guess which format names are in. So two rules control what kind of file name you must pass various routines:
Overview
Archive::Zip::Archive objects are what you ordinarily deal with. These maintain the structure of a zip file, without necessarily holding data. When a zip is read from a disk file, the (possibly compressed) data still lives in the file, not in memory. Archive members hold information about the individual members, but not (usually) the actual member data. When the zip is written to a (different) file, the member data is compressed or copied as needed. It is possible to make archive members whose data is held in a string in memory, but this is not done when a zip file is read. Directory members don't have any data.
Exporter Archive::Zip Common base class, has defs. Archive::Zip::Archive A Zip archive. Archive::Zip::Member Abstract superclass for all members. Archive::Zip::StringMember Member made from a string Archive::Zip::FileMember Member made from an external file Archive::Zip::ZipFileMember Member that lives in a zip file Archive::Zip::NewFileMember Member whose data is in a file Archive::Zip::DirectoryMember Member that is a directory
FA_MSDOS FA_UNIX GPBF_ENCRYPTED_MASK GPBF_DEFLATING_COMPRESSION_MASK GPBF_HAS_DATA_DESCRIPTOR_MASK COMPRESSION_STORED COMPRESSION_DEFLATED IFA_TEXT_FILE_MASK IFA_TEXT_FILE IFA_BINARY_FILE COMPRESSION_LEVEL_NONE COMPRESSION_LEVEL_DEFAULT COMPRESSION_LEVEL_FASTEST COMPRESSION_LEVEL_BEST_COMPRESSION ZIP64_SUPPORTED ZIP64_AS_NEEDED ZIP64_EOCD ZIP64_HEADERS
FA_AMIGA FA_VAX_VMS FA_VM_CMS FA_ATARI_ST FA_OS2_HPFS FA_MACINTOSH FA_Z_SYSTEM FA_CPM FA_WINDOWS_NTFS GPBF_IMPLODING_8K_SLIDING_DICTIONARY_MASK GPBF_IMPLODING_3_SHANNON_FANO_TREES_MASK GPBF_IS_COMPRESSED_PATCHED_DATA_MASK COMPRESSION_SHRUNK DEFLATING_COMPRESSION_NORMAL DEFLATING_COMPRESSION_MAXIMUM DEFLATING_COMPRESSION_FAST DEFLATING_COMPRESSION_SUPER_FAST COMPRESSION_REDUCED_1 COMPRESSION_REDUCED_2 COMPRESSION_REDUCED_3 COMPRESSION_REDUCED_4 COMPRESSION_IMPLODED COMPRESSION_TOKENIZED COMPRESSION_DEFLATED_ENHANCED COMPRESSION_PKWARE_DATA_COMPRESSION_LIBRARY_IMPLODED
AZ_OK AZ_STREAM_END AZ_ERROR AZ_FORMAT_ERROR AZ_IO_ERROR
Many of the methods in Archive::Zip return error codes. These are implemented as inline subroutines, using the "use constant" pragma. They can be imported into your namespace using the ":ERROR_CODES" tag:
use Archive::Zip qw( :ERROR_CODES ); ... unless ( $zip->read( 'myfile.zip' ) == AZ_OK ) { die "whoops!"; }
Archive::Zip allows each member of a ZIP file to be compressed (using the Deflate algorithm) or uncompressed.
Other compression algorithms that some versions of ZIP have been able to produce are not supported. Each member has two compression methods: the one it's stored as (this is always COMPRESSION_STORED for string and external file members), and the one you desire for the member in the zip file.
These can be different, of course, so you can make a zip member that is not compressed out of one that is, and vice versa.
You can inquire about the current compression and set the desired compression method:
my $member = $zip->memberNamed( 'xyz.txt' ); $member->compressionMethod(); # return current compression # set to read uncompressed $member->desiredCompressionMethod( COMPRESSION_STORED ); # set to read compressed $member->desiredCompressionMethod( COMPRESSION_DEFLATED );
There are two different compression methods:
If a member's desiredCompressionMethod is COMPRESSION_DEFLATED, you can choose different compression levels. This choice may affect the speed of compression and decompression, as well as the size of the compressed member data.
$member->desiredCompressionLevel( 9 );
The levels given can be:
This is the same as saying
$member->desiredCompressionMethod( COMPRESSION_STORED );
1 gives the best speed and worst compression, and 9 gives the best compression and worst speed.
This is a synonym for level 1.
This is a synonym for level 9.
This gives a good compromise between speed and compression, and is currently equivalent to 6 (this is in the zlib code). This is the level that will be used if not specified.
The Archive::Zip class (and its invisible subclass Archive::Zip::Archive) implement generic zip file functionality. Creating a new Archive::Zip object actually makes an Archive::Zip::Archive object, but you don't have to worry about this unless you're subclassing.
my $zip = Archive::Zip->new();
If an additional argument is passed, new() will call read() to read the contents of an archive:
my $zip = Archive::Zip->new( 'xyz.zip' );
If a filename argument is passed and the read fails for any reason, new will return undef. For this reason, it may be better to call read separately.
These Archive::Zip methods may be called as functions or as object methods. Do not call them as class methods:
$zip = Archive::Zip->new(); $crc = Archive::Zip::computeCRC32( 'ghijkl' ); # OK $crc = $zip->computeCRC32( 'ghijkl' ); # also OK $crc = Archive::Zip->computeCRC32( 'ghijkl' ); # NOT OK
$crc = Archive::Zip::computeCRC32( $string );
Or you can compute the running CRC:
$crc = 0; $crc = Archive::Zip::computeCRC32( 'abcdef', $crc ); $crc = Archive::Zip::computeCRC32( 'ghijkl', $crc );
Archive::Zip::setChunkSize( 4096 );
or as a method on a zip (though this is a global setting). Returns old chunk size.
my $chunkSize = Archive::Zip::chunkSize();
Archive::Zip::setErrorHandler( \&myErrorHandler );
If myErrorHandler is undef, resets handler to default. Returns old error handler. Note that if you call Carp::carp or a similar routine or if you're chaining to the default error handler from your error handler, you may want to increment the number of caller levels that are skipped (do not just set it to a number):
$Carp::CarpLevel++;
$ENV{TMPDIR}
environment variable. But see the File::Spec documentation for your system. Note that on many systems, if you're running in taint mode, then you must make sure that $ENV{TMPDIR} is untainted for it to be used. Will NOT create $tmpdir if it does not exist (this is a change from prior versions!). Returns file handle and name:
my ($fh, $name) = Archive::Zip::tempFile(); my ($fh, $name) = Archive::Zip::tempFile('myTempDir'); my $fh = Archive::Zip::tempFile(); # if you don't need the name
my @members = $zip->members();
my @textFileMembers = $zip->membersMatching( '.*\.txt' ); # or my $numberOfTextFiles = $zip->membersMatching( '.*\.txt' );
print $zip->zipfileComment(); $zip->zipfileComment( 'New Comment' );
my $zip = Archive::Zip->new('somefile.zip'); if ($zip->eocdOffset()) { warn "A virus has added ", $zip->eocdOffset, " bytes of garbage\n"; }
The "eocdOffset()" is used to adjust the starting position of member headers, if necessary.
Various operations on a zip file modify members. When a member is passed as an argument, you can either use a reference to the member itself, or the name of a member. Of course, using the name requires that names be unique within a zip (this is not enforced).
It is an (undiagnosed) error to provide a $newMember that is a member of the zip being modified.
my $member1 = $zip->removeMember( 'xyz' ); my $member2 = $zip->replaceMember( 'abc', $member1 ); # now, $member2 (named 'abc') is not in $zip, # and $member1 (named 'xyz') is, having taken $member2's place.
# Move member named 'abc' to end of zip: my $member = $zip->removeMember( 'abc' ); $zip->addMember( $member );
NOTE that you should not (generally) use absolute path names in zip member names, as this will cause problems with some zip tools as well as introduce a security hole and make the zip harder to use.
my $member = $zip->addString( 'This is a test', 'test.txt' );
print "xyz.txt contains " . $zip->contents( 'xyz.txt' );
Also can change the contents of a member:
$zip->contents( 'xyz.txt', 'This is the new contents' );
If called expecting an array as the return value, it will include the status as the second value in the array.
($content, $status) = $zip->contents( 'xyz.txt');
A Zip archive can be written to a file or file handle, or read from one.
my $status = $zip->writeToFileNamed( 'xx.zip' ); die "error somewhere" if $status != AZ_OK;
Note that if you use the same name as an existing zip file that you read in, you will clobber ZipFileMembers. So instead, write to a different file name, then delete the original. If you use the "overwrite()" or "overwriteAs()" methods, you can re-write the original zip in this way. $fileName should be a valid file name on your system.
my $fh = IO::File->new( 'someFile.zip', 'w' ); unless ( $zip->writeToFileHandle( $fh ) == AZ_OK ) { # error handling }
If you pass a file handle that is not seekable (like if you're writing to a pipe or a socket), pass a false second argument:
my $fh = IO::File->new( '| cat > somefile.zip', 'w' ); $zip->writeToFileHandle( $fh, 0 ); # fh is not seekable
If this method fails during the write of a member, that member and all following it will return false from "wasWritten()". See writeCentralDirectory() for a way to deal with this. If you want, you can write data to the file handle before passing it to writeToFileHandle(); this could be used (for instance) for making self-extracting archives. However, this only works reliably when writing to a real file (as opposed to STDOUT or some other possible non-file).
See examples/selfex.pl for how to write a self-extracting archive.
Returns AZ_OK on success. If given an $offset, will seek to that point before writing. This can be used for recovery in cases where writeToFileHandle or writeToFileNamed returns an IO error because of running out of space on the destination file.
You can truncate the zip by seeking backwards and then writing the directory:
my $fh = IO::File->new( 'someFile.zip', 'w' ); my $retval = $zip->writeToFileHandle( $fh ); if ( $retval == AZ_IO_ERROR ) { my @unwritten = grep { not $_->wasWritten() } $zip->members(); if (@unwritten) { $zip->removeMember( $member ) foreach my $member ( @unwritten ); $zip->writeCentralDirectory( $fh, $unwritten[0]->writeLocalHeaderRelativeOffset()); } }
my $zipFile = Archive::Zip->new(); my $status = $zipFile->read( '/some/FileName.zip' );
my $fh = IO::File->new( '/some/FileName.zip', 'r' ); my $zip1 = Archive::Zip->new(); my $status = $zip1->readFromFileHandle( $fh ); my $zip2 = Archive::Zip->new(); $status = $zip2->readFromFileHandle( $fh );
Read zip using in-memory data (recursable):
open my $fh, "<", "archive.zip" or die $!; my $zip_data = do { local $.; <$fh> }; my $zip = Archive::Zip->new; open my $dh, "+<", \$zip_data; $zip->readFromFileHandle ($dh);
These used to be in Archive::Zip::Tree but got moved into Archive::Zip. They enable operation on an entire tree of members or files. A usage example:
use Archive::Zip; my $zip = Archive::Zip->new(); # add all readable files and directories below . as xyz/* $zip->addTree( '.', 'xyz' ); # add all readable plain files below /abc as def/* $zip->addTree( '/abc', 'def', sub { -f && -r } ); # add all .c files below /tmp as stuff/* $zip->addTreeMatching( '/tmp', 'stuff', '\.c$' ); # add all .o files below /tmp as stuff/* if they aren't writable $zip->addTreeMatching( '/tmp', 'stuff', '\.o$', sub { ! -w } ); # add all .so files below /tmp that are smaller than 200 bytes as stuff/* $zip->addTreeMatching( '/tmp', 'stuff', '\.o$', sub { -s < 200 } ); # and write them into a file $zip->writeToFileNamed('xxx.zip'); # now extract the same files into /tmpx $zip->extractTree( 'stuff', '/tmpx' );
my $pred = sub { /\.txt/ }; $zip->addTree( '.', '', $pred );
will add all the .txt files in and below the current directory, using relative names, and making the names identical in the zipfile:
original name zip member name ./xyz xyz ./a/ a/ ./a/b a/b
To translate absolute to relative pathnames, just pass them in: $zip->addTree( '/c/d', 'a' );
original name zip member name /c/d/xyz a/xyz /c/d/a/ a/a/ /c/d/a/b a/a/b
Returns AZ_OK on success. Note that this will not follow symbolic links to directories. Note also that this does not check for the validity of filenames.
Note that you generally don't want to make zip archive member names absolute.
$zip->addTreeMatching( '.', 'xyz', '\.pl$' )
To add all writable files in and below the directory named "/abc" whose names end in ".pl", and make them extract into a subdirectory named "xyz", do this:
$zip->addTreeMatching( '/abc', 'xyz', '\.pl$', sub { -w } )
Returns AZ_OK on success. Note that this will not follow symbolic links to directories.
"updateTree()" takes the same arguments as "addTree()", but first checks to see whether the file or directory already exists in the zip file, and whether it has been changed.
If the fourth argument $mirror is true, then delete all my members if corresponding files were not found.
Returns an error code or AZ_OK if all is well.
If you supply one argument for $root, "extractTree" will extract all the members whose names start with $root into the current directory, stripping off $root first. $root is in Zip (Unix) format. For instance,
$zip->extractTree( 'a' );
when applied to a zip containing the files: a/x a/b/c ax/d/e d/e will extract:
a/x as ./x
a/b/c as ./b/c
If you give two arguments, "extractTree" extracts all the members whose names start with $root. It will translate $root into $dest to construct the destination file name. $root and $dest are in Zip (Unix) format. For instance,
$zip->extractTree( 'a', 'd/e' );
when applied to a zip containing the files: a/x a/b/c ax/d/e d/e will extract:
a/x to d/e/x
a/b/c to d/e/b/c and ignore ax/d/e and d/e
If you give three arguments, "extractTree" extracts all the members whose names start with $root. It will translate $root into $dest to construct the destination file name, and then it will convert to local file system format, using $volume as the name of the destination volume.
$root and $dest are in Zip (Unix) format.
$volume is in local file system format.
For instance, under Windows,
$zip->extractTree( 'a', 'd/e', 'f:' );
when applied to a zip containing the files: a/x a/b/c ax/d/e d/e will extract:
a/x to f:d/e/x
a/b/c to f:d/e/b/c and ignore ax/d/e and d/e
If you want absolute paths (the prior example used paths relative to the current directory on the destination volume, you can specify these in $dest:
$zip->extractTree( 'a', '/d/e', 'f:' );
when applied to a zip containing the files: a/x a/b/c ax/d/e d/e will extract:
a/x to f:\d\e\x
a/b/c to f:\d\e\b\c and ignore ax/d/e and d/e
If the path to the extracted file traverses a parent directory or a symbolic link, the extraction will be aborted with "AC_ERROR" for security reason. Returns an error code or AZ_OK if everything worked OK.
{ local $Archive::Zip::UNICODE = 1; $zip->addFile('Déjà vu.txt'); }
Several constructors allow you to construct members without adding them to a zip archive. These work the same as the addFile(), addDirectory(), and addString() zip instance methods described above, but they don't add the new members to a zip.
my $member = Archive::Zip::Member->newFromString( 'This is a test' ); my $member = Archive::Zip::Member->newFromString( 'This is a test', 'test.txt' ); my $member = Archive::Zip::Member->newFromString( { string => 'This is a test', zipName => 'test.txt' } );
my $member = Archive::Zip::Member->newFromFile( 'xyz.txt' );
If given, $zipname will be the name of the zip member; it must be a valid Zip (Unix) name. If not given, it will be converted from $directoryName.
Returns undef on error.
my $member = Archive::Zip::Member->newDirectoryNamed( 'CVS/' );
These methods get (and/or set) member attribute values.
The zip64 format requires parts of the member data to be stored in the so-called extra fields. You cannot get nor set this zip64 data through the extra field accessors described in this section. In fact, the low-level member methods ensure that the zip64 data in the extra fields is handled completely transparently and invisibly to the user when members are read or written.
print "Mod Time: " . scalar( localtime( $member->lastModTime() ) );
$member->setLastModFileDateTimeFromUnix( time() );
my $oldAttribs = $member->unixFileAttributes( 0666 );
Note that the return value has more than just the file permissions, so you will have to mask off the lowest bits for comparisons.
my $zip = Archive::Zip->new; $zip->read ("encrypted.zip"); for my $m (map { $zip->memberNamed ($_) } $zip->memberNames) { $m->password ("secret"); $m->contents; # is "" when password was wrong
That shows that the password has to be set per member, and not per archive. This might change in the future.
It is possible to use lower-level routines to access member data streams, rather than the extract* methods and contents(). For instance, here is how to print the uncompressed contents of a member in chunks using these methods:
my ( $member, $status, $bufferRef ); $member = $zip->memberNamed( 'xyz.txt' ); $member->desiredCompressionMethod( COMPRESSION_STORED ); $status = $member->rewindData(); die "error $status" unless $status == AZ_OK; while ( ! $member->readIsDone() ) { ( $bufferRef, $status ) = $member->readChunk(); die "error $status" if $status != AZ_OK && $status != AZ_STREAM_END; # do something with $bufferRef: print $$bufferRef; } $member->endRead();
my ( $outRef, $status ) = $self->readChunk(); print $$outRef if $status != AZ_OK && $status != AZ_STREAM_END;
my $string = $member->contents(); # or my ( $string, $status ) = $member->contents(); die "error $status" unless $status == AZ_OK;
Can also be used to set the contents of a member (this may change the class of the member):
$member->contents( "this is my new contents" );
For members representing symbolic links, pass the name of the symbolic link as file handle. Ensure that all directories in the path to the symbolic link already exist.
The Archive::Zip::FileMember class extends Archive::Zip::Member. It is the base class for both ZipFileMember and NewFileMember classes. This class adds an "externalFileName" and an "fh" member to keep track of the external file.
The Archive::Zip::ZipFileMember class represents members that have been read from external zip files.
Archive::Zip requires several other modules:
Carp
Compress::Raw::Zlib
Cwd
File::Basename
File::Copy
File::Find
File::Path
File::Spec
IO::File
IO::Seekable
Time::Local
If you are just going to be extracting zips (and/or other archives) you are recommended to look at using Archive::Extract instead, as it is much easier to use and factors out archive-specific functionality.
Since version 1.66 Archive::Zip supports the so-called zip64 format, which overcomes various limitations in the original zip file format. On some Perl interpreters, however, even version 1.66 and newer of Archive::Zip cannot support the zip64 format. Among these are all Perl interpreters that lack 64-bit support and those older than version 5.10.0.
Constant "ZIP64_SUPPORTED", exported with tag :CONSTANTS, equals true if Archive::Zip on the current Perl interpreter supports the zip64 format. If it does not and you try to read or write an archive in zip64 format, anyway, Archive::Zip returns an error "AZ_ERROR" and reports an error message along the lines of "zip64 format not supported on this Perl interpreter".
The zip64 format and the zip file format in general specify what values to use for the "versionMadeBy" and "versionNeededToExtract" fields in the local file header, central directory file header, and zip64 EOCD record. In practice however, these fields seem to be more or less randomly used by various archiver implementations.
To achieve a compromise between backward compatibility and (whatever) standard compliance, Archive::Zip handles them as follows:
One of the most common ways to use Archive::Zip is to generate Zip files in-memory. Most people use IO::Scalar for this purpose.
Unfortunately, as of 1.11 this module no longer works with IO::Scalar as it incorrectly implements seeking.
Anybody using IO::Scalar should consider porting to IO::String, which is smaller, lighter, and is implemented to be perfectly compatible with regular seekable filehandles.
Support for IO::Scalar most likely will not be restored in the future, as IO::Scalar itself cannot change the way it is implemented due to back-compatibility issues.
When an encrypted member is read using the wrong password, you currently have to re-read the entire archive to try again with the correct password.
* auto-choosing storing vs compression
* extra field hooks (see notes.txt)
* check for duplicates on addition/renaming?
* Text file extraction (line end translation)
* Reading zip files from non-seekable inputs
(Perhaps by proxying through IO::String?)
* separate unused constants into separate module
* cookbook style docs
* Handle tainted paths correctly
* Work on better compatibility with other IO:: modules
* Support encryption
* More user-friendly decryption
Bugs should be reported on GitHub
<https://github.com/redhotpenguin/perl-Archive-Zip/issues>
For other issues contact the maintainer.
Currently maintained by Fred Moyer <fred@redhotpenguin.com>
Previously maintained by Adam Kennedy <adamk@cpan.org>
Previously maintained by Steve Peters <steve@fisharerojo.org>.
File attributes code by Maurice Aubrey <maurice@lovelyfilth.com>.
Originally by Ned Konz <nedkonz@cpan.org>.
Some parts copyright 2006 - 2012 Adam Kennedy.
Some parts copyright 2005 Steve Peters.
Original work copyright 2000 - 2004 Ned Konz.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Look at Archive::Zip::MemberRead which is a wrapper that allows one to read Zip archive members as if they were files.
Compress::Raw::Zlib, Archive::Tar, Archive::Extract
2020-03-14 | perl v5.30.0 |