Tutorial: Create a zip file from folders on the fly

Sometimes in web programming when dealing with multiple files or directory download operations, it is better to serve the user with a single zip file rather than let the user manually download the file one by one using direct link download . To overcome this problem, we have to create a zip file on the fly without have to manually create it using any commpresion tools or softwares.

PHP has some functions dealing with file compression that enables us to create zip file on the fly. In this tutorial i will use PHP CreateZipFile classs package from Rochak Chauhan. I have made some examples below to explain how to craete zip file on the fly from multiple files or directory.

Example 1, create zip file from existing files:

<?php

include_once 'CreateZipFile.inc.php';
$createZip = new CreateZipFile;
$createZip->addDirectory('/');
$filecontent1 = file_get_contents('fileone.txt');
$filecontent2 = file_get_contents('filetwo.txt');
$createZip->addFile($filecontent1, '/fileone.txt');
$createZip->addFile($filecontent2, '/filetwo.txt');
$zipFileName = 'myzip.zip';
$handle       = fopen($zipFileName, 'wb');
$out           = fwrite($handle, $createZip->getZippedFile());
fclose($handle);
$createZip->forceDownload($zipFileName);
@unlink($zipFileName);
?>
To create zip file:
  • add a directory into zip file using addDirectory method
  • add files into directory using addFile method
  • create zip file temporary for download and delete it after the file is downloaded
Example 2, create zip file for a directory with it’s contents/subdirectories
<?php

include_once 'CreateZipFile.inc.php';
$createZip = new CreateZipFile;
$createZip->zipDirectory('/testdir', '');
$zipFileName = 'myzip.zip';
$handle       = fopen($zipFileName, 'wb');
$out           = fwrite($handle, $createZip->getZippedFile());
fclose($handle);
$createZip->forceDownload($zipFileName);
@unlink($zipFileName);
?>
To create zip file for a directory, use zipDirectory method that takes two arguments, first is the name of directory that want to be zipped and second is directory name for zipped file.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s