Saturday, January 29, 2011

Creating compressed zip files in php


We can create zip files in php in a very easy way by using phps in built functions. See the function below.

what you need to do is to pass the array of files to this function which you wants to add to zip file. How to list files is described next in  list_dir_files().

<?php

/* creates a compressed zip file */
function create_zip($files = array(),$destination = ”,$overwrite = false) {
 //if the zip file already exists and overwrite is false, return false
 if(file_exists($destination) && !$overwrite) { return false; }
 //vars
 $valid_files = array();
 //if files were passed in…
 if(is_array($files)) {
  //cycle through each file
  foreach($files as $file) {
   //make sure the file exists
   if(file_exists($file)) {
    $valid_files[] = $file;
   }
  }
 }
 //if we have good files…
 if(count($valid_files)) {
  //create the archive
  $zip = new ZipArchive();
  if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
   return false;
  }
  //add the files
  foreach($valid_files as $file) {
   $zip->addFile($file,$file);
  }
  //debug
  //echo ‘The zip archive contains ‘,$zip->numFiles,’ files with a status of ‘,$zip->status;
  //close the zip — done!
  $zip->close();
  //check to make sure the file exists
  return file_exists($destination);
 }
 else
 {
  return false;
 }
}

?>
   

  

Listing Files To Zip

 

$files_to_zip = list_dir_files(–PATH–);

 

and then pass these files to above function.

<?

 /*********Function to Return file paths in directory and sub directories*********/
 function list_dir_files($src){
  global $err,$files_to_zip;

  $dir = opendir($src);

  while(false !== ( $file = readdir($dir) )) {

   if(($file != ‘.’ && $file != ‘..’)){
    if( is_dir($src. ‘/’ . $file) ) {
     list_dir_files($src . ‘/’ . $file);
    }else {
     //$dest = str_replace(”,”,$src);
     array_push($files_to_zip,$src . ‘/’ . $file);
    }
   }
  }
  closedir($dir);
  return $files_to_zip;
 }

 ?>

No comments:

Post a Comment