Skip to content

Instantly share code, notes, and snippets.

@shahariaazam
Created February 3, 2013 17:43
Show Gist options
  • Save shahariaazam/4702764 to your computer and use it in GitHub Desktop.
Save shahariaazam/4702764 to your computer and use it in GitHub Desktop.
Create .ZIP archive in PHP
<?php
/**
* @Author Shaharia Azam
* @Author URL http://www.shahariaazam.com
*
* @Description this function will make a .zip folder by adding multiple files.
* @link http://php.net/manual/en/book.zip.php
*
* @param array $SourceFiles
* @param string $ZipDestination
* @param bool $overwrite
*
* @return bool
*/
/* creates a compressed zip file */
function ZipMaker($SourceFiles = array(),$ZipDestination = '',$overwrite = false) {
//Overwrite the existing ZIP if it's exist already
if(file_exists($ZipDestination) && !$overwrite) { return false; }
$valid_files = array();
if(is_array($SourceFiles)) {
foreach($SourceFiles as $file) {
//Whether the file is exists or not
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//Perform action on valid files
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($ZipDestination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
$zip->close();
//double check that Zip created and exists at last
return file_exists($ZipDestination);
}
else
{
return false;
}
}
$AddToZip = array(
'forZip1.txt',
'forZip2.txt'
);
/**
* Now perform execution
*/
$result = ZipMaker($AddToZip,'newZip.zip');
var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment