Skip to content

Instantly share code, notes, and snippets.

@ashokmhrj
Last active December 29, 2015 10:57
Show Gist options
  • Save ashokmhrj/eaf2e1840240b01fb82c to your computer and use it in GitHub Desktop.
Save ashokmhrj/eaf2e1840240b01fb82c to your computer and use it in GitHub Desktop.
<?php
/**
* PHP script for zip directory recursive function
*/
//source: http://ramui.com/articles/php-zip-files-and-directory.html
function recurse_zip($src,&$zip,$path_length) {
$dir = opendir($src);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_zip($src . '/' . $file,$zip,$path_length);
}
else {
$zip->addFile($src . '/' . $file,substr($src . '/' . $file,$path_length));
}
}
}
closedir($dir);
}
//Call this function with argument = absolute path of file or directory name.
function compress($src){
if(substr($src,-1)==='/') {
$src=substr($src,0,-1);
}
$arr_src=explode('/',$src);
$filename=end($src);
unset($arr_src[count($arr_src)-1]);
$path_length=strlen(implode('/',$arr_src).'/');
$f=explode('.',$filename);
$filename=$f[0];
$filename=(($filename=='')? 'backup.zip' : $filename.'.zip');
$zip = new ZipArchive;
$res = $zip->open($filename, ZipArchive::CREATE);
if($res !== TRUE){
echo 'Error: Unable to create zip file';
exit;}
if(is_file($src)){
$zip->addFile($src,substr($src,$path_length));
} else {
if(!is_dir($src)) {
$zip->close();
@unlink($filename);
echo 'Error: File not found';
exit;
}
recurse_zip($src,$zip,$path_length);
}
$zip->close();
header("Location: $filename");
exit;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment