Create or extract an archive in PHP

2066

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: $archive->addFile('letter.txt');
$archive->addFile('picture.jpg');$archive->addFile('style.css');

Or you can add files from PHP values:

$content = 'Hello Santa!';$archive->addFromString('email.txt', $content); Also you can add files from a directory: $archive->buildFromDirectory('/path/to/my/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:

$archive->extractTo('/path/to/my/directory'); 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: