How To Create Zip File In PHP Using Custom Ziparchive Class Example?

PHP 8 , PHP

Nicesnippets

947

22-06-2021


How To Create Zip File In PHP Using Custom Ziparchive Class Example?

Hi guys,

Today i will explained how to create a zip file in custom ziparchiver class through. This example is so easy to use in php. This example to i am create a custom ziparchiver class in php

This tutorial to your folder to create a zip file in unique name to create. I am create a timezone_map folder and one dummy file. Then i am create a second folder in archive_files to dowload your create zip file.

So you are follow for my step by step.

So let's start to the example.

Index.php


<?php

// Include and initialize ZipArchive class

require_once 'ZipArchiver.class.php';

$zipper = new ZipArchiver;

// Path of the directory to be zipped

$dirPath = 'timezone_map';

// Path of output zip file

$zipPath = 'archive_files/archive-'.time().'.zip';

// Create zip archive

$zip = $zipper->zipDir($dirPath, $zipPath);

if($zip){

echo 'ZIP archive created successfully.';

}else{

echo 'Failed to create ZIP.';

}

?>

ZipArchiver.class.php

<?php

Class ZipArchiver {

/**

* Folder path that should be zipped.

*

* @return response()

*/

public static function zipDir($sourcePath, $outZipPath){

$pathInfo = pathinfo($sourcePath);

$parentPath = $pathInfo['dirname'];

$dirName = $pathInfo['basename'];

$z = new ZipArchive();

$z->open($outZipPath, ZipArchive::CREATE);

$z->addEmptyDir($dirName);

if($sourcePath == $dirName){

self::dirToZip($sourcePath, $z, 0);

}else{

self::dirToZip($sourcePath, $z, strlen("$parentPath/"));

}

$z->close();

return true;

}

/**

* Add files and sub-directories in a folder to zip file.

*

* @return response()

*/

private static function dirToZip($folder, &$zipFile, $exclusiveLength){

$handle = opendir($folder);

while(FALSE !== $f = readdir($handle)){

if($f != '.' && $f != '..' && $f != basename(__FILE__)){

$filePath = "$folder/$f";

$localPath = substr($filePath, $exclusiveLength);

if(is_file($filePath)){

$zipFile->addFile($filePath, $localPath);

}elseif(is_dir($filePath)){

$zipFile->addEmptyDir($localPath);

self::dirToZip($filePath, $zipFile, $exclusiveLength);

}

}

}

closedir($handle);

}

}

?>

Now you can check your own.

I hope it can help you...


Recommended Posts