Author Topic: PHP Tar class  (Read 1088 times)

aldo

  • Sr. Member
  • ****
  • Posts: 328
    • View Profile
    • MS Chat
PHP Tar class
« on: February 27, 2010, 04:41:54 PM »
So I needed to be able to extract files from tar (or tar.gz) files in PHP. There are some out there, but they are HUGE, the one at the PHP PEAR site is 62KB which is completely unnecessary for my needs...

Anyways, you can open and create tar and tar.gz files.


$tar 
= new Tar();
$tar->open('my.tar''r'); // Open my.tar for reading, if it doesn't exist, it will fail.

// To see if the tarball is gzipped, you can do this:
if($tar->is_gzipped())
{
  
// Extract it.
  
$tar->ungzip();
}

print_r($tar->files()); // This will display an array containing all the files and folders which are contained within the tarball.

$tar->extract('./destination/'); // All files and folders in my.tar will be extracted from the tarball and put inside the destination folder.
$tar->close();

$tar->open('myOther.tar''w'); // Open myOther.tar for writing, if it exists, the file will be deleted.

// The first parameter is the location of the file to add, while the second is the name of the file in the tarball you want
// to create. The second parameter is not required if the file is within the current working directory (getcwd())
$tar->add_file('fileToAdd.ext''fileNameInTar.ext');

// You can also add a file from a string, like this:
$tar->add_from_string('fileName.ext''the contents of the file');

// Adding an empty directory
$tar->add_empty_dir('directoryName/Another/And/So/On');

// If you want, you can set it so that once the tarball is done, it will be gzipped:
$tar->set_gzip(true);

$tar->save(); // Writes the contents to the file, and gzips it if set.


You can also check to see if the tarball is in the UStar format (which simply contains more information about the file/directory) through $tar->is_ustar(); If it is, then more information will be returned about each file/folder with the files method. Right now, creating UStar formatted tarballs is unsupported, though I might add it soon :)

Oh yeah. I have tested this class pretty well. I opened tar and tar.gz files made with 7z, and I have made tar and tar.gz files with this class and extracted them successfully with 7zip.

Download: tar.class.php

EpicCyndaquil

  • The not so scary
  • Administrator
  • Hero Member
  • *****
  • Posts: 1006
    • View Profile
    • Epic Cyndaquil
Re: PHP Tar class
« Reply #1 on: February 27, 2010, 11:26:47 PM »
Wow that's really cool, awesome  ;D

paulwratt

  • Lurker
  • *
  • Posts: 2
    • View Profile
Re: PHP Tar class
« Reply #2 on: January 12, 2011, 08:32:52 PM »
Just what I was looking for aldo (nice to see you are still coding useful stuff)

I will adapt it to do bzip2 as well, here hoping :)

Paul