Create or extract an archive in PHP


The most simple way to work with archives in PHP is PharData class

To create an archive or open an existing one just write:

$archive = new PharData('archive.tar');

Add files to archive like that:


Or you can add files from PHP values:

$content = 'Hello Santa!';
$archive->addFromString('email.txt', $content);

Also you can add files from a directory:


If you don't need to compress the archive then you're done — just leave it like that. Or else you can compress your archive with a single call:

$archive->compress(Phar::GZ); # Compress as GZip
# OR
$archive->compress(Phar::BZ2); # Compress as Bzip2

This will create a file archive.tar.gz (or archive.tar.bz2). Note that this function cannot append files to the compressed archive. If archive.tar.gz already exists then you'll get an error:

Exception : exception 'BadMethodCallException' with message 'phar "archive.tar.gz" exists and must be unlinked prior to conversion'

To extract files from archive write:


Or you can extract just a single file:

$archive->extractTo('/path/to/my/directory', 'email.txt');

Or several files:

$archive->extractTo('/path/to/my/directory', ['email.txt', 'letter.txt', 'style.css']);
Rate this post:
Share this page:

See also how to:

How to extract files from different tar archives in Linux command line
How to extract files from zip archive in Linux command line
How to make POST and other types of HTTP requests and add custom HTTP headers with file_get_contents function in PHP
How to run your PHP or Bash script as root in the most secure way
How to use modern MaxMind GeoIP API in PHP