Posted By

MMDeveloper on 09/19/08


Tagged

php file zip zipfile


Versions (?)

Who likes this?

9 people have marked this snippet as a favorite

luman
elgermano
mrjthethird
Scooter
rubenrails
nb109
ninjacharlee
prit
ringo380


PHP Zip file creation, OOP


 / Published in: PHP
 

URL: http://www.mechanicmatt.com

  1. <?php
  2. /*
  3. By: Matt Ford
  4.  
  5. Purpose: Basic class to create zipfiles
  6. */
  7.  
  8.  
  9.  
  10. class zipFile {
  11. public $files = array();
  12. public $settings = NULL;
  13. public $fileInfo = array (
  14. "name" => "",
  15. "numFiles" => 0,
  16. "fullFilePath" => ""
  17. );
  18. private $fileHash = "";
  19. private $zip = "";
  20.  
  21. public function __construct($settings) {
  22. $this->zipFile($settings);
  23. }
  24.  
  25. public function zipFile($settings) {
  26. $this->zip = new ZipArchive();
  27. $this->settings = new stdClass();
  28.  
  29.  
  30. foreach ($settings as $k => $v) {
  31. $this->settings->$k = $v;
  32. }
  33. }
  34.  
  35. public function create() {
  36. $this->fileHash = md5(implode(",", $this->files));
  37. $this->fileInfo["name"] = $this->fileHash . ".zip";
  38. $this->fileInfo["numFiles"] = count($this->files);
  39. $this->fileInfo["fullFilePath"] = $this->settings->path . "/" . $this->fileInfo["name"];
  40. if (file_exists($this->fileInfo["fullFilePath"])) {
  41. return array (
  42. false,
  43. "already created: " . $this->fileInfo["fullFilePath"]
  44. );
  45. }
  46. else {
  47. $this->zip->open($this->fileInfo["fullFilePath"], ZIPARCHIVE::CREATE);
  48. $this->addFiles();
  49. $this->zip->close();
  50. return array (
  51. true,
  52. "new file created: " . $this->fileInfo["fullFilePath"]
  53. );
  54. }
  55. }
  56.  
  57. private function addFiles() {
  58. foreach ($this->files as $k) {
  59. $this->zip->addFile($k, basename($k));
  60. }
  61. }
  62. }
  63.  
  64.  
  65. $settings = array (
  66. "path" => dirname(__FILE__)
  67. );
  68.  
  69. $zipFile = new zipFile($settings);
  70.  
  71.  
  72. $zipFile->files = array (
  73. "./images/navoff.jpg",
  74. "./images/navon.jpg"
  75. );
  76.  
  77. list($success, $error) = $zipFile->create();
  78.  
  79. if ($success === true) {
  80. //success
  81. }
  82. else {
  83. //error because: $error
  84. }
  85. ?>

Report this snippet  

You need to login to post a comment.