About
In this code snippet, we’ll learn how to zip files in PHP.
Let’s see the example below.
Code:
<?php //Entry point//////////////////////////////////////////////////////////////////////////////////// //Array of file paths to be zipped. $filesToBeZipped = [ "C:\\xampp\htdocs\Code Examples\php\Zipping Files\zipme1.txt", "C:\\xampp\htdocs\Code Examples\php\Zipping Files\zipme2.txt", "C:\\xampp\htdocs\Code Examples\php\Zipping Files\zipme3.txt" ]; zipFiles($filesToBeZipped, "ZipTest.zip", "C:\\xampp\htdocs\Code Examples\php\Zipping Files"); ///////////////////////////////////////////////////////////////////////////////////////////////// //Functions////////////////////////////////////////////////////////////////////////////////////// function zipFiles($filesToBeZipped, $name, $destination){ //Join name and location. $zipFilePath = $destination . "\\" . $name; //Create archive. More info. about ZipArchive: https://www.php.net/manual/en/ziparchive.open.php $zip = new ZipArchive(); //Open new or existing file. If operation fails we'll exit with an error. if($zip->open($zipFilePath, ZipArchive::CREATE) !== TRUE) exit("Error"); //Iterate through all paths and add them to the zip file. foreach($filesToBeZipped as $path) $zip->addFile($path, basename($path)); //basename() gets just the file name from the path. //Finish and zip the files. $zip->close(); } //////////////////////////////////////////////////////////////////////////////////////////////////