28

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?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Jack Wilsdon
  • 6,706
  • 11
  • 44
  • 87

2 Answers2

54

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');
j0k
  • 22,600
  • 28
  • 79
  • 90
  • 1
    For some reason PharData::extractTo doesn't work in PHP 5.4.0 on Windows. Can't figure out why – TinyGrasshopper Dec 14 '12 at 03:12
  • I saw [your question](http://stackoverflow.com/q/13870800/569101) but I do not have a Windows with 5.4.0 to test it, sorry. – j0k Dec 14 '12 at 08:24
  • It also, contrary to documentation, does not seem to take directories as the second argument. – Daniel Saner Jun 10 '13 at 01:58
  • Also PharData fails on certain types of tar contents http://stackoverflow.com/questions/37189687/phardata-class-fails-when-tar-contents-has-relative-paths – artfulrobot Jun 13 '16 at 11:27
  • to anyone still encountering this error . convert it to zip and then extract it. saw the solution here .https://stackoverflow.com/questions/38843938/phardata-extractto-method-failed-to-extract-tar-gz-on-linux-environment – Kevin Florenz Daus Jul 07 '17 at 22:57
  • Very cool. I used this on a custom Moodle backup / restore script. They switched from .zip to .tar but disguise their backups as an .mbz. A few lines of code changes and it was working perfectly. Thanks! – Andy Oct 25 '17 at 03:29
3

PEAR provides the Archive_Tar class, which supports both Gzip and BZ2 compressions, provided you have the zlib and bz2 extensions loaded, respectively.

netcoder
  • 66,435
  • 19
  • 125
  • 142