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:
<?php // 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 $phar->buildFromDirectory($dir); // we are using gzip comppression $phar->compress(Phar::GZ); ?>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 recognisedThis 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