Friday, 17 June 2016

How to create a zip file in php?

In one of my previous post, We  have already seen How we can extract Zip Files using PHP. In this tutorial, we are going to create a Zip file with PHP. To perform this task, we are going to use a built-in extension in PHP known as ZipArchive classs.
This is a very basic PHP function which accepts two parameters array of files to be zipped and name of zip file to be created.
//Creating a Zip File Using PHP
function genZip($files = array(),$zipName){
 $zip = new ZipArchive();
 $zip->open($zipName.'.zip', ZipArchive::CREATE);
 foreach($files as $file){
  $zip->addFile($file);
 }
 $zip->close();
}
Usage:
//Usage of genZip function
$files = array(
  'file1.pdf',
  'file2.pdf',
  'file3.pdf',
  'folder2/file4.pdf',
  'folder2/file5.pdf'
 );
$zipName = 'myfiles';
genZip($files,$zipName);

0 comments:

Post a Comment