Advertisement
olie480

PHP: Create a ZIP file

Jan 16th, 2014
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.39 KB | None | 0 0
  1. // http://davidwalsh.name/create-zip-php
  2.  
  3. /* creates a compressed zip file */
  4. function create_zip($files = array(),$destination = '',$overwrite = false) {
  5.     //if the zip file already exists and overwrite is false, return false
  6.     if(file_exists($destination) && !$overwrite) { return false; }
  7.     //vars
  8.     $valid_files = array();
  9.     //if files were passed in...
  10.     if(is_array($files)) {
  11.         //cycle through each file
  12.         foreach($files as $file) {
  13.             //make sure the file exists
  14.             if(file_exists($file)) {
  15.                 $valid_files[] = $file;
  16.             }
  17.         }
  18.     }
  19.     //if we have good files...
  20.     if(count($valid_files)) {
  21.         //create the archive
  22.         $zip = new ZipArchive();
  23.         if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  24.             return false;
  25.         }
  26.         //add the files
  27.         foreach($valid_files as $file) {
  28.             $zip->addFile($file,$file);
  29.         }
  30.         //debug
  31.         //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
  32.        
  33.         //close the zip -- done!
  34.         $zip->close();
  35.        
  36.         //check to make sure the file exists
  37.         return file_exists($destination);
  38.     }
  39.     else
  40.     {
  41.         return false;
  42.     }
  43. }
  44.  
  45.  
  46. // sample usage
  47. $files_to_zip = array(
  48.     'preload-images/1.jpg',
  49.     'preload-images/2.jpg',
  50.     'preload-images/5.jpg',
  51.     'kwicks/ringo.gif',
  52.     'rod.jpg',
  53.     'reddit.gif'
  54. );
  55. //if true, good; if false, zip creation failed
  56. $result = create_zip($files_to_zip,'my-archive.zip');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement