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

php生成zip文件类实例

程序员文章站 2022-04-20 22:53:46
本文实例讲述了php生成zip文件类。分享给大家供大家参考。具体如下:

本文实例讲述了php生成zip文件类。分享给大家供大家参考。具体如下:

<?php
 /*
  by:   matt ford
  purpose: basic class to create zipfiles
 */
class zipfile {
 public $files = array();
 public $settings = null;
 public $fileinfo = array (
   "name" => "",
   "numfiles" => 0,
   "fullfilepath" => ""
  );
 private $filehash = "";
 private $zip = "";
 public function __construct($settings) {
  $this->zipfile($settings);
 }
 public function zipfile($settings) {
  $this->zip = new ziparchive();
  $this->settings = new stdclass();
  foreach ($settings as $k => $v) {
   $this->settings->$k = $v;
  }
 }
 public function create() {
  $this->filehash = md5(implode(",", $this->files));
  $this->fileinfo["name"] = $this->filehash . ".zip";
  $this->fileinfo["numfiles"] = count($this->files);
  $this->fileinfo["fullfilepath"] = $this->settings->path . 
  "/" . $this->fileinfo["name"];
  if (file_exists($this->fileinfo["fullfilepath"])) {
   return array (
     false,
     "already created: " . $this->fileinfo["fullfilepath"]
     );
  }
  else {
   $this->zip->open($this->fileinfo["fullfilepath"], ziparchive::create);
   $this->addfiles();
   $this->zip->close();
   return array (
     true,
     "new file created: " . $this->fileinfo["fullfilepath"]
     );
  }
 }
 private function addfiles() {
  foreach ($this->files as $k) {
   $this->zip->addfile($k, basename($k));
  }
 }
}
$settings = array (
  "path" => dirname(__file__)
 );
$zipfile = new zipfile($settings);
$zipfile->files = array (
  "./images/navoff.jpg",
  "./images/navon.jpg"
 );
list($success, $error) = $zipfile->create();
if ($success === true) {
 //success
}
else {
 //error because: $error
}
?>

希望本文所述对大家的php程序设计有所帮助。