Breaking News
Loading...
November 25, 2017

PHP ZIP all files in directory and download .zip generated

12:40 PM
Well, first of all, this is my folder structure:
images/
 image1.png
 image11.png
 image111.png
 image223.png
generate_zip.php
And this is mine generate_zip.php:

======= Working solution !======

includes all sub-folders:
<?php
$the_folder = 'path/foldername';
$zip_file_name = 'archived_name.zip';

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);
  }
 } 
}

$za = new FlxZipArchive;
$res = $za->open($zip_file_name, ZipArchive::CREATE);
if($res === TRUE)    {
 $za->addDir($the_folder, basename($the_folder));
 header('Content-Type: application/zip');
 header("Content-Disposition: attachment; filename='adcs.zip'");
 header('Content-Length: ' . filesize($zipname));
 header("Location: adcs.zip");
 $za->close();
} else  {
 echo 'Could not create a zip archive';
}
?>

0 comments:

Post a Comment

 
Toggle Footer