PHP File Zipping

PHP Code Snippets Zipping Files


In this code snippet, we’ll learn how to zip files in PHP.

Let’s see the example below.



//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, "", "C:\\xampp\htdocs\Code Examples\php\Zipping Files");



function zipFiles($filesToBeZipped, $name, $destination){
	//Join name and location.
	$zipFilePath = $destination . "\\" . $name;
	//Create archive. More info. about ZipArchive:
	$zip = new ZipArchive();

	//Open new or existing file. If operation fails we'll exit with an error.
	if($zip->open($zipFilePath, ZipArchive::CREATE) !== TRUE)
	//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.


Resulting output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger