Creating zip or tar.gz archive without exec

You can use PHP's Zip class to create zip files, and ZLib to create gzip files.

Creating a .zip file:

$zip = new ZipArchive();
$res = $zip->open('test.zip', ZipArchive::CREATE);
$zip->addFromString('test.txt', 'file content goes here');
$zip->addFile('data.txt', 'entryname.txt');
$zip->close();

Creating a .gz file:

$file = "test.txt";
$gzfile = "test.gz";
$fp = gzopen($gzfile, 'w9'); // w == write, 9 == highest compression
gzwrite($fp, file_get_contents($file));
gzclose($fp);

If you want to create tar.gz and you are using PHP 5.3+, you can use PharData class:

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

    // ADD FILES TO archive.tar FILE
    $a->addFile('data.xls');
    $a->addFile('index.php');

    // COMPRESS archive.tar FILE. COMPRESSED FILE WILL BE archive.tar.gz
    $a->compress(Phar::GZ);

    // NOTE THAT BOTH FILES WILL EXISTS. SO IF YOU WANT YOU CAN UNLINK archive.tar
    unlink('archive.tar');
} 
catch (Exception $e) 
{
    echo "Exception : " . $e;
}

Tags:

Php

Zip

Tar