Create Zip Files


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function create_zip($files = array(),$destination = '',$overwrite = false) {
  2. //if the zip file already exists and overwrite is false, return false
  3. if(file_exists($destination) && !$overwrite) { return false; }
  4. //vars
  5. $valid_files = array();
  6. //if files were passed in...
  7. if(is_array($files)) {
  8. //cycle through each file
  9. foreach($files as $file) {
  10. //make sure the file exists
  11. if(file_exists($file)) {
  12. $valid_files[] = $file;
  13. }
  14. }
  15. }
  16. //if we have good files...
  17. if(count($valid_files)) {
  18. //create the archive
  19. $zip = new ZipArchive();
  20. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  21. return false;
  22. }
  23. //add the files
  24. foreach($valid_files as $file) {
  25. $zip->addFile($file,$file);
  26. }
  27. //debug
  28. //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
  29.  
  30. //close the zip -- done!
  31. $zip->close();
  32.  
  33. //check to make sure the file exists
  34. return file_exists($destination);
  35. }
  36. else
  37. {
  38. return false;
  39. }
  40. }
  41. /***** Example Usage ***/
  42. $files=array('file1.jpg', 'file2.jpg', 'file3.gif');
  43. create_zip($files, 'myzipfile.zip', true);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.