Create a .tar file from a array in PHP

853 views Asked by At

I want to create a .tar file from an array in PHP which has the path of the files I want to compress.

Array ( 
[0] => Array ( [img] => 1000e5d5771dd2c08bb368faef3e44944.jpg ) 
[1] => Array ( [img] => 10011633ba1169e1c7a67b31ad41df0c8.jpg ) 
[2] => Array ( [img] => 100155e447db12dc3a0d3cc3a4bd55f10.jpg )
)

I don't even know if this can be done, I only know this can be done using something like this:

if (is_dir($Path) === true) {
    $archive = new PharData('/var/www/html/media/migration.tar');
    $archive->buildFromDirectory($Path);
}

This tar would be created from a path, but I have all my files with many others, so I can't use the entire path. Any ideas?

2

There are 2 answers

0
viral On BEST ANSWER

This will do it

$your_array = [
                [ 'img' => '1000e5d5771dd2c08bb368faef3e44944.jpg' ],
                [ 'img' => '10011633ba1169e1c7a67b31ad41df0c8.jpg' ],
                [ 'img' => '100155e447db12dc3a0d3cc3a4bd55f10.jpg' ]
              ];

$img_path = 'location/to/your/images/directory/';

try
{
    $archive = new PharData('archive.tar');

    foreach($your_array as $img)
    {
        $archive->addFile( $img_path . $img['img'] );
    }
} 
catch (Exception $e) 
{
    echo "Exception : " . $e;
}

Note that it will create archive in your current directory (the same directory where this snippet is located), you can change this by changing path to $archive = new PharData('archive.tar'); this line.

0
javier_domenech On

You have to add each file and when you got them all then compress:

$archive = new PharData('/var/www/html/media/migration.tar');
//setting the path where all your files are: (guessing is the same the script runs)
$path_folder = '.';    
foreach($array_files as $file)
{
    if (is_dir($path_folder.'/'.$file) === true) {
        $archive->addFile($path_folder.'/'.$file);

    }
}

$archive->compressFiles(Phar::GZ);