Extract from Archive Tar/Gz/Tar.gz with Pear in PHP
1st of all we need Archive_Tar package to download and install. Download package from here, and run this command in terminal to install it.
pear install path/to/Archive_Tar-1.3.x
In Archive_Tar-1.3.x x represents which version you downloaded, at the time of writing the latest version is 1.3.6. Also include the full path to the downloaded archive.
To check, either Archive_Tar is installed successfully:
pear list
It will show all the installed packages like:
me@me-desktop:~$ pear list
Installed packages, channel pear.php.net:
=========================================
Package Version State
Archive_Tar 1.3.6 stable
Console_Getopt 1.2.3 stable
PEAR 1.9.0 stable
Structures_Graph 1.0.3 stable
XML_Util 1.2.1 stable
Now in your PHP script, you need to include it like:
<?php
require_once 'Archive/Tar.php';
?>
Lets create some directories:
mkdir /var/www/files
mkdir /var/www/files/extracted_files
mkdir /var/www/files/backup
Change the permissions, that script will be able to write into it.
su -
chmod 777 /var/www/files/*
Full Script:
<?php
require_once 'Archive/Tar.php';
//Filename to extract, you can get filename from database too.
$filename = 'theme.tar';
//From database, you need to run query to get the filename. Enable/uncomment the line below if you need to use it.
//$filename = $row->filename;
//Get file extension.
$ext = pathinfo($filename, PATHINFO_EXTENSION);
//Path to file.
$name_of_file = "/var/www/files/".$filename;
//Directory to extract file, this is in case you want the files to be extracted in different location.
$dir = "/var/www/files/extracted_files/";
//Directory to backup the old files, this is in case you want the old files to be deleted.
$backup = "/var/www/files/backup/".$filename;
//Check if file exists
if(file_exists($name_of_file)){
//Check file extension
if($ext == 'tar' || $ext == 'gz'){
//Open file to read
$tar = new Archive_Tar($name_of_file, true);
//Extract the file using Pear library
$result = $tar->extract($dir);
echo "File extraction done!<br>";
}
//Move file to backup dir, if you dont want this feature just comment/delete this line and above starting with $backup.
rename($name_of_file, $backup);
echo "File moved to backup dir";
}
?>
Just copy the above script and paste it in your favorite text editor, save it as index.php in files dir you just created above and now open browser input this address,
http://localhost/files
Just follow the instructions and hope it will work for you as it should.
Happy coding!