Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compressing a directory of files with PHP

I am creating a php backup script that will dump everything from a database and save it to a file. I have been successful in doing that but now I need to take hundreds of images in a directory and compress them into one simple .tar.gz file.

What is the best way to do this and how is it done? I have no idea where to start.

Thanks in advance

like image 908
VinkoCM Avatar asked Jun 26 '09 12:06

VinkoCM


1 Answers

If you are using PHP 5.2 or later, you could use the Zip Library

and then do something along the lines of:

$images_dir = '/path/to/images';
//this folder must be writeable by the server
$backup = '/path/to/backup';
$zip_file = $backup.'/backup.zip';

if ($handle = opendir($images_dir))  
{
    $zip = new ZipArchive();

    if ($zip->open($zip_file, ZipArchive::CREATE)!==TRUE) 
    {
        exit("cannot open <$zip_file>\n");
    }

    while (false !== ($file = readdir($handle))) 
    {
        $zip->addFile($images_dir.'/'.$file);
        echo "$file\n";
    }
    closedir($handle);
    echo "numfiles: " . $zip->numFiles . "\n";
    echo "status:" . $zip->status . "\n";
    $zip->close();
    echo 'Zip File:'.$zip_file . "\n";
}
like image 167
Paul Dixon Avatar answered Oct 10 '22 23:10

Paul Dixon