Comprimir y descomprimir archivos ZIP


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



Copy this code and paste it in your HTML
  1. /* creates a compressed zip file */
  2. function create_zip($files = array(),$destination = '',$overwrite = false) {
  3. //if the zip file already exists and overwrite is false, return false
  4. if(file_exists($destination) && !$overwrite) { return false; }
  5. //vars
  6. $valid_files = array();
  7. //if files were passed in...
  8. if(is_array($files)) {
  9. //cycle through each file
  10. foreach($files as $file) {
  11. //make sure the file exists
  12. if(file_exists($file)) {
  13. $valid_files[] = $file;
  14. }
  15. }
  16. }
  17. //if we have good files...
  18. if(count($valid_files)) {
  19. //create the archive
  20. $zip = new ZipArchive();
  21. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  22. return false;
  23. }
  24. //add the files
  25. foreach($valid_files as $file) {
  26. $zip->addFile($file,$file);
  27. }
  28. //debug
  29. //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
  30.  
  31. //close the zip -- done!
  32. $zip->close();
  33.  
  34. //check to make sure the file exists
  35. return file_exists($destination);
  36. }
  37. else
  38. {
  39. return false;
  40. }
  41. }
  42. /***** Example Usage ***/
  43. $files=array('file1.jpg', 'file2.jpg', 'file3.gif');
  44. create_zip($files, 'myzipfile.zip', true);
  45.  
  46.  
  47.  
  48.  
  49.  
  50. /**********************
  51. *@file - path to zip file
  52. *@destination - destination directory for unzipped files
  53. */
  54. function unzip_file($file, $destination){
  55. // create object
  56. $zip = new ZipArchive() ;
  57. // open archive
  58. if ($zip->open($file) !== TRUE) {
  59. die (’Could not open archive’);
  60. }
  61. // extract contents to destination directory
  62. $zip->extractTo($destination);
  63. // close archive
  64. $zip->close();
  65. echo 'Archive extracted to directory';
  66. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.