Free Technology Blog

Tuesday, March 1, 2016

We will be discussing about creating ZIP archive using PHP script. I  will be mentioning  a PHP script to generate ZIP archive file below. This function zips all the inner files and folders of a folder.
You need to have PHP version >= 5.2.0. If you are using following script in live server then you need to set write permission to zip file.
As a matter of fact,  PHP’s ZIP class provides all the functionalities. To make the process a bit faster for you, I’ve mentioned a create_zip_folder  function for ease.

------- Code Started ----------

function create_zip_folder(){
  // Get real path for folder
  $folder_to_zip = realpath("path-to-folder");
  
  //saving zip  
  $zipname = "zip-file-name.zip";
  // we are using try and catch
// you can run the script without the try..catch
  try{
  // Initialize archive object
  zip = new ZipArchive();
  $zip->open( $zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  // Create recursive directory iterator
  $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder_to_zip), RecursiveIteratorIterator::LEAVES_ONLY );
  foreach ($files as $name => $file) {
   // Skip directories (they would be added automatically)
     if (!$file->isDir()) {
         // Get real and relative path for current file
      $filePath = $file->getRealPath();
              $relativePath = substr($filePath, strlen($folder_to_zip) + 1);
        
             // Add current file to archive
             zip->addFile($filePath, $relativePath);
     } // if ends
     } // foreach ends
   echo "zip is generated";
} catch( Exception $e ){
// catch message  for unable to generate zip
}
}// function ends
//call the function
create_zip_folder();

------- End Code  ----------
You can also pass the parameter instead of hardcore path and zip file name. Just need to make a little tweak in the script.
If you want download the archive file
// then send the headers to foce download the zip file
// replace $zipname with your 'zip-filename.zip'
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$zipname ");
header("Pragma: no-cache");
header("Expires: 0");
readfile($zipname);
exit;

Source: I got these script from Stack Overflow.



0 comments:

Post a Comment