Wednesday 3 September 2014

Creating Zip file of a folder in PHP

During large php projects , we have to create zip files dynamically. Iam explaining  in this post how to create zip file of a folder dynamicaly using PHP. In PHP we didn't want to  add external libraries for creating zip files. We have ZIPARCHIVE library available in php library itself.

So I will explain step by step in how to acheive this...

1) Create a folder named zip or any name you like in the root directory. This will be the directory which will store the zip files.

2) Create a folder named samplesite & place all the files inside this folder. This folder will be converted to zip file.

3) Create a php page and paste the below code

<?php

$filename="Filename.zip"; // name of the zip file to create

// Adding files to a .zip file, no zip file exists it creates a new ZIP file

// increase script timeout value
ini_set('max_execution_time', 5000);

// create object
$zip = new ZipArchive();

// open archive 
if ($zip->open('zip/'.$filename, ZIPARCHIVE::CREATE) !== TRUE) {
    die ("Could not open archive");
}

// initialize an iterator
// pass it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("samplesite/"));
//give the folder name to be zipped

// iterate over the directory
// add each file found to the archive
foreach ($iterator as $key=>$value) {
    $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}

// close and save archive
$zip->close();
echo "Archive created successfully.";
?>


After Executing this script, check the folder zip, it contains the zip file filename.zip....
Hope this post helps... For any help.. pls let me know...


No comments:

Post a Comment