TAR File Management With PHP Archive_Tar - Adding It All Up (
Page 4 of 8 )
You can also add files to a previously-created archive with the add() method,
which accepts a list of files and merely adds them to the specified archive
file. If the file does not already exist, add() will create it for you.
The following example illustrates, by adding some files to the "data.tar"
file created in the previous example:
<?php
// include class
require("Tar.php");
if (file_exists("data.tar"))
{
// create Archive_Tar() object
// specify filename for output file
$tar = new Archive_Tar("data.tar");
// add files to existing archive
$tar->add(array("employees.xml", "departments.xml"))
or die ("Could not add files!"); } else {
die("File does not exist!");
}
?>
It's important to note that the add() method will add files to the archive
even if they already exist. This behaviour can lead to problems in certain
situations - for example, if you ran the script above four times, the resulting
archive would hold four copies of each of the files in the file list.
The ability to selectively add files to an archive comes in handy when you
need to iterate over a file collection and only archive those which meet certain
criteria - for example, all those files older than a specific date. Consider the
following example, which illustrates how you might do this:
<?php
// include class
require("Tar.php");
// get UNIX timestamp for 1 Jun 2003
$ts = mktime(0, 0, 0, 6, 1, 2003);
// set directory
$dir = "scripts/";
// create tar file
$tar = new Archive_Tar("data.tar");
// iterate over files in directory
$handle = opendir("scripts/");
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && filemtime($dir
. "/" . $file) < $ts)
{
// if file was modified before $ts
// add to archive
$tar->add($dir . "/" . $file) or die ("Could not add file!");
}
}
closedir($handle);
?>
In this case, the filemtime() function has been used to obtain the last
modification time of each file in the named directory. Files with a timestamp
older than the specified date get add()-ed to the archive as they are
encountered.