PHP Untar-gz without exec()?

Jack Wilsdon picture Jack Wilsdon · Feb 23, 2012 · Viewed 27.3k times · Source

How would I untar-gz a file in php without the use of exec('tar') or any other commands, using pure PHP?

My problem is as follows; I have a 26mb tar.gz file that needs to be uploaded onto my server and extracted. I have tried using net2ftp to extract it, but it doesn't support tar.gz uncompressing after upload.

I'm using a free web host, so they don't allow any exec() commands, and they don't allow access to a prompt. So how would I go about untaring this?

Does PHP have a built in command?

Answer

j0k picture j0k · Sep 7, 2012

Since PHP 5.3.0 you do not need to use Archive_Tar.

There is new class to work on tar archive: The PharData class.

To extract an archive (using PharData::extractTo() which work like the ZipArchive::extractTo()):

try {
    $phar = new PharData('myphar.tar');
    $phar->extractTo('/full/path'); // extract all files
} catch (Exception $e) {
    // handle errors
}

And if you have a tar.gz archive, just decompress it before extract (using PharData::decompress()):

// decompress from gz
$p = new PharData('/path/to/my.tar.gz');
$p->decompress(); // creates /path/to/my.tar

// unarchive from the tar
$phar = new PharData('/path/to/my.tar');
$phar->extractTo('/full/path');