欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

一个php 生成zip文件的类

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

php, zip