Skip to content

Instantly share code, notes, and snippets.

@ninadsp
Last active February 17, 2021 16:52
Show Gist options
  • Save ninadsp/6098467 to your computer and use it in GitHub Desktop.
Save ninadsp/6098467 to your computer and use it in GitHub Desktop.
Code snippets for my blogpost Recursively Zip a directory with PHP (http://ninad.pundaliks.in/blog/2011/05/recursively-zip-a-directory-with-php/)
<?
/**
* FlxZipArchive, Extends ZipArchiv.
* Add Dirs with Files and Subdirs.
*
* <code>
* $archive = new FlxZipArchive;
* // .....
* $archive->addDir( 'test/blub', 'blub' );
* </code>
*/
class FlxZipArchive extends ZipArchive {
/**
* Add a Dir with Files and Subdirs to the archive
*
* @param string $location Real Location
* @param string $name Name in Archive
* @author Nicolas Heimann
* @access private
**/
public function addDir($location, $name) {
$this->addEmptyDir($name);
$this->addDirDo($location, $name);
} // EO addDir;
/**
* Add Files & Dirs to archive.
*
* @param string $location Real Location
* @param string $name Name in Archive
* @author Nicolas Heimann
* @access private
**/
private function addDirDo($location, $name) {
$name .= '/';
$location .= '/';
// Read all Files in Dir
$dir = opendir ($location);
while ($file = readdir($dir))
{
if ($file == '.' || $file == '..') continue;
// Rekursiv, If dir: FlxZipArchive::addDir(), else ::File();
$do = (filetype( $location . $file) == 'dir') ? 'addDir' : 'addFile';
$this->$do($location . $file, $name . $file);
}
} // EO addDirDo();
}
?>
<?php
//Don't forget to remove the trailing slash
$the_folder = '/path/to/folder/to/be/zipped';
$zip_file_name = '/path/to/zip/archive.zip';
$za = new FlxZipArchive;
$res = $za->open($zip_file_name, ZipArchive::CREATE);
if($res === TRUE) {
$za->addDir($the_folder, basename($the_folder));
$za->close();
}
else
echo 'Could not create a zip archive';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment