The following examples demonstrate how to use the Archive component.
The TAR format has more than one standard. The most common formats are:
Each format can be extracted from the archive. Appending entries to the archive
is only available for Unix V7 and Ustar format.
Extracting an Archive comes in two flavors:
The Archive can be treated like an iterator.
After opening the archive, it points to the first entry. The iterator can be
moved using the ezcArchive->next() and ezcArchive->rewind() to move to the next
entry or go back to the first entry.
The next example demonstrates how to extract an entire archive file-by-file:
- <?php
-
- include( "tutorial_autoload.php" );
- date_default_timezone_set( "UTC" );
-
- // Open the gzipped TAR archive.
- $archive = ezcArchive::open( "compress.zlib:///tmp/my_archive.tar.gz" );
-
- while( $archive->valid() )
- {
- // Returns the current entry (ezcArchiveEntry).
- $entry = $archive->current();
-
- // ezcArchiveEntry has an __toString() method.
- echo $entry, "\n";
-
- // Extract the current archive entry to /tmp/target_location/
- $archive->extractCurrent( "/tmp/target_location/" );
-
- $archive->next();
- }
-
- ?>
First the tutorial_autoload.php is included. The included file loads the
correct php files for the archive package. Hereafter the time zone is set to
"UTC". The archive uses some date functions and without a time zone PHP may
show some warnings.
The gzipped TAR archive is opened using the zlib stream. The while() method
iterates over each entry, shows the name, and extracts the entry itself.
The Archive extends from the PHP Iterator class, the example above can be
rewritten as:
- <?php
-
- include( "tutorial_autoload.php" );
- date_default_timezone_set( "UTC" );
-
- $archive = ezcArchive::open( "compress.zlib:///tmp/my_archive.tar.gz" );
-
- // The foreach method calls internally the iterator methods.
- foreach( $archive as $entry )
- {
- echo $entry, "\n";
-
- $archive->extractCurrent( "/tmp/target_location/" );
- }
-
- ?>
Unfortunately, it is not yet possible to directly append files to a gzipped or
bzipped Tar archive. The ZLib and BZip2 library do not support opening a file
for reading and writing.
ezcArchive has two methods for appending files:
To replace also the first file, the ezcArchive->truncate() should be used. The
next example replaces all entries from an existing Zip archive with the files
file1.txt and file2.txt:
- <?php
-
- include( "tutorial_autoload.php" );
- date_default_timezone_set( "UTC" );
-
- $archive = ezcArchive::open( "/tmp/my_archive.zip" );
- $archive->truncate();
-
- $filesToAppend[] = "/tmp/file1.txt";
- $filesToAppend[] = "/tmp/file2.txt";
-
- // The second parameter specifies prefix. The prefix is normally not included
- // in the archive.
- $archive->appendToCurrent( $filesToAppend, "/tmp/" );
-
- ?>