PHP File Zipping

PHP Code Snippets Zipping Files
Share:

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();
}

//////////////////////////////////////////////////////////////////////////////////////////////////

Resulting output:

Before:
After:
Share:

Leave a Reply

Your email address will not be published.

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