php简单创建zip压缩文件的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了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);
  }
  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');

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP操作zip文件及压缩技巧总结》、《php文件操作总结》、《php正则表达式用法总结》、《PHP+ajax技巧与应用小结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

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

相关文章

PHP移动文件指针ftell()、fseek()、rewind()函数总结

在对文件进行读写过程中,有时需要在文件中跳转、同不同位置读取,以及将数据写入到不同的位置。例如,使用文件模拟数据库保存数据,就需要移动文件指针。指针的位置是以从文件头开始的字节数度量的,...

PHP之生成GIF动画的实现方法

代码如下所示:复制代码 代码如下:<?class GifMerge {     var $ver    &nb...

PHP通过串口实现发送短信

随技术进步,短信收发领域按时间先后产生了三种模式:BLOCK MODE,基于AT指令的TEXT MODE,基于AT指令的PDU MODE。其中,TEXT MODE比较简单,多款诺基亚手机...

php 随机数的产生、页面跳转、件读写、文件重命名、switch语句

复制代码 代码如下:<?php num = rand(1,5); witch($num){ case 1: $fp1=fopen("f1.dat",'r'); $oname = f...

PHP通过get方法获得form表单数据方法总结

PHP通过get方法获得form表单数据方法总结

我们在进行网页交互设计的时候,通常都会使用PHP中get变量方法来获得form表单中的数据,以此来实现各种网页动态查询或者请求。对于稍有HTML基础的朋友来说,应该都知道HTML for...