站长网 PHP教程 php简单创建zip压缩文件的技巧

php简单创建zip压缩文件的技巧

本文实例讲述了php简单创建zip压缩文件的方法。分享给大家供大家参考,具体如下: /* creates a compressed zip file */ function create_zip($files = array(),$destination = ,$overwrite = false) { //if the zip file already exists and overwrite is f

   本文实例讲述了php简单创建zip压缩文件的方法。分享给大家供大家参考,具体如下:
 
  /* creates a compressed zip file */
  
  function create_zip($files = array(),$destination = '',$overwrite = false) {
  
    //if the zip file already exists and overwrite is false, return false
  
    if(file_exists($destination) && !$overwrite) { return false; }
  
    //vars
  
    $valid_files = array();
  
    //if files were passed in…
  
    if(is_array($files)) {
  
      //cycle through each file
  
      foreach($files as $file) {
  
        //make sure the file exists
  
        if(file_exists($file)) {
  
          $valid_files[] = $file;
  
        }
  
      }
  
    }
  
    //if we have good files…
  
    if(count($valid_files)) {
  
      //create the archive
  
      $zip = new ZipArchive();
  
      if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  
        return false;
  
      }
  
      //add the files
  
      foreach($valid_files as $file) {
  
        $zip->addFile($file,$file);
  
      }
  
      //debug
  
      //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
  
      //close the zip — done!
  
      $zip->close();
  
      //check to make sure the file exists
  
      return file_exists($destination);
  
    }//phpfensi.com
  
    else
  
    {
  
      return false;
  
    }
  
  }
  使用方法:
 
  $files_to_zip = array(
  
    'preload-images/1.jpg',
  
    'preload-images/2.jpg',
  
    'preload-images/5.jpg',
  
    'kwicks/ringo.gif',
  
    'rod.jpg',
  
    'reddit.gif'
  
  );
  
  //if true, good; if false, zip creation failed
  
  $result = create_zip($files_to_zip,'my-archive.zip');
  

作者: dawei

【声明】:站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

联系我们

联系我们

0577-28828765

在线咨询: QQ交谈

邮箱: pniu8212@foxmail.com

工作时间:周一至周五,9:00-17:30,节假日休息

返回顶部