Search code examples
phploopszipphp-ziparchive

php zip a folder without looping


with php i can do zip with the following code

$zip = new ZipArchive;
if ($zip->open ('test.zip', ZipArchive::CREATE)) {
    $zip->addFile('img1.jpg', 'user.jpg');
    $zip->addFile('logo.jpg', 'file.jpg');
    $zip->addFile('avatar.jpg', 'av.jpg');
    //or we can even loop a directory
   foreach(glob($dir . '/*') as $file)
    {
       //add each file from the directory
    }
    //end loop

    $zip->close();
    echo 'Zipped !';
} else {
    echo 'failed';
}

?>

My question is can we zip an entire folder without looping it

  $zip = new ZipArchive;
    if ($zip->open ('test.zip', ZipArchive::CREATE)) {
     $zip->addFolder('bla bla'); //like this,so that the entire files in it will be added
         $zip->close();
        echo 'Zipped !';
    } else {
        echo 'failed';
    }
?>

Solution

  • The implementation will have to loop eventually. Unfortunately ZipArchive does not expose such a function that will do this for you.

    See this thread where you can get a readymade function that does just that.