Tar is a common archive format used on linux. Alone it is just an archiving format, that is it can only pack multiple files together but not compress them. When combined with gzip or bzip2 files are compressed as well. Then it becomes a .tar.gz which is actually a gzip compressed tar file.
Php has a class called PharData that can be used to create tar archives and tar.gz compressed files as well. It works from php 5.3 onwards. Usage is quite simple. Lets take a look
//First pack all files in a tar archive try { $a = new PharData('archive.tar'); $a->addFile('data.xls'); $a->addFile('index.php'); echo "Files added to archive.tar"; } catch (Exception $e) { echo "Exception : " . $e; }
The above code creates a tar archive named "archive.tar". Files are added using the addFile method.
Compress
Next thing to do is compress the tar archive to a tar.gz. There are 2 ways to do this. Either call the compress method of PharData object.
try { $a = new PharData('archive.tar'); $a->addFile('data.xls'); $a->addFile('index.php'); $a->compress(Phar::GZ); } catch (Exception $e) { echo "Exception : " . $e; }
Or use the gzencode function
try { $a = new PharData('archive.tar'); $a->addFile('data.xls'); $a->addFile('index.php'); } catch (Exception $e) { echo "Exception : " . $e; } //Now compress to tar.gz file_put_contents('archive.tar.gz' , gzencode(file_get_contents('archive.tar')));
Either method should work fine. To compress using bzip2 instead use the compress method and pass "Phar::BZ2" as the parameter value.
try { $a = new PharData('archive.tar'); $a->addFile('data.xls'); $a->addFile('index.php'); $a->compress(Phar::BZ2); } catch (Exception $e) { echo "Exception : " . $e; }
Adding directories
The above example showed how to add single files to the tar achive. To add an entire directory, use the method buildFromDirectory
try { $a = new PharData('archive.tar'); $a->addFile('data.xls'); $a->buildFromDirectory('path/dir'); $a->compress(Phar::GZ); } catch (Exception $e) { echo "Exception : " . $e; }
Note that if the tar archive already exists, then calling the compress method would throw an exception like this
Exception : exception 'BadMethodCallException' with message 'phar "/var/www/archive.tar.gz" exists and must be unlinked prior to conversion' in /var/www/phar.php:13 Stack trace: #0 /var/www/phar.php(13): PharData->compress(4096) #1 {main}
Therefor the archive if it exists, should be first deleted.
Note that filenames with periods will get broken.
https://bugs.php.net/bug.php?id=58852