Sep 9, 2011

How to make tar and tar.gz archives with PHP

This question is somewhat painful for me. Maybe I am too stupid. Anyway, if you want to make tar archive without using exec, for example on Windows machine without tar tool or any other stupid reason, here is how to do it with PHP. Its actually very easy if you know how to do it.

For example lets have a directory called dir and we want to make an archive with its content. The solution for our problem is Phar.

Here is the code that do the job:


// we want to archive all files from this directory
$dir = "dir/";

// the name of our new tar
$phar = new Phar("ourarchive.phar.tar");

// build from our dir

// we are using gzip comppression

Look carefully at the name of our archive - the parameter that we give when we create Phar object. It ends with phar.tar. If you use only .tar it will return error:
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'Cannot create phar 'ourarchive.tar', file extension (or combination) not recognised
This is not fun if you are trying to create tar and you receive this message. So using file name that ends with phar.tar will fix the problem.

If you receive error:
Fatal error: Uncaught exception 'BadMethodCallException' with message 'Unable to add newly converted phar "/www/pro/ourarchive.phar.tar" to the list of phars, a phar with that name already exists'
most likely your tar file already exist.

Learn here how to make Zip archives with PHP

1 comment:

cbc said...


I am trying to use Phar/PharData. The constructor of PharData works fine. However when i try
, nothing happens.

What can I be doing wrong? my php version is 5.3.10 and i am developing with a mac os.x.
Thank you in advance

Popular Posts