Home Backend Development PHP Tutorial Detailed example of php ZipArchive compression function_PHP tutorial

Detailed example of php ZipArchive compression function_PHP tutorial

Jul 13, 2016 am 10:25 AM
zip

Use ZipArchive to compress files. This is an extension class of php. This extension has been supported since php5.2. If you get an error when using it, check the extension=php_zip.dll in php.ini. Have you removed the semicolon before restarting Apache so that you can use this class library?
Example 1. Generate zip file

Copy the code The code is as follows:

/ * Generate 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; ) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) ! == true) {
                return false; $zip->addFile($file,$file_info_arr['basename']);//Remove the hierarchical directory
      }
          //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;
}
}

define('ROOTPATH',dirname ( __FILE__ )); //Website path

$files_to_zip = array(
ROOTPATH.DIRECTORY_SEPARATOR.'PHP+jQuery+Cookbook.pdf',
ROOTPATH.DIRECTORY_SEPARATOR.'TurboListerZeroTemplate.csv'
);
//if true, good; if false, zip creation failed
$filename='my-archive.zip';
$result = create_zip($files_to_zip,$filename);


Example 2, compress all files under the folder



Copy code

The code is as follows :

/*
php zip压缩文件夹下面的所有文件
*/
class HZip
{
  /**
* Add files and subdirectories to the zip file
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength Number of text to be exclusived from the file path .
*/
  private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
    $handle = opendir($folder);
    while (false !== $f = readdir($handle)) {
      if ($f != '.' && $f != '..') {
        $filePath = "$folder/$f";
        // Remove prefix from file path before add to zip.
        $localPath = substr($filePath, $exclusiveLength);
        if (is_file($filePath)) {
          $zipFile->addFile($filePath, $localPath);
        } elseif (is_dir($filePath)) {
          // 添加子文件夹
          $zipFile->addEmptyDir($localPath);
          self::folderToZip($filePath, $zipFile, $exclusiveLength);
        }
      }
    }
    closedir($handle);
  }

  /**
   * Zip a folder (include itself).
   * Usage:
   *   HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
   *
   * @param string $sourcePath Path of directory to be zip.
   * @param string $outZipPath Path of output zip file.
  */
  public static function zipDir($sourcePath, $outZipPath)
  {
    $pathInfo = pathInfo($sourcePath);
    $parentPath = $pathInfo['dirname'];
    $dirName = $pathInfo['basename'];
    $sourcePath=$parentPath.'/'.$dirName;//防止传递'folder' 文件夹产生bug
    $z = new ZipArchive();
    $z->open($outZipPath, ZIPARCHIVE::CREATE);//建立zip文件
    $z->addEmptyDir($dirName);//建立文件夹
    self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
    $z->close();
  }
}

//使用方法
HZip::zipDir('yourlife', 'yourlife.zip');
?>
 

1.ZipArchive::addEmptyDir
添加一个新的文件目录
2.ZipArchive::addFile
将文件添加到指定zip压缩包中。
3.ZipArchive::addFromString
添加的文件同时将内容添加进去
4.ZipArchive::close
关闭ziparchive
5.ZipArchive::extractTo
将压缩包解压
6.ZipArchive::open
打开一个zip压缩包
7.ZipArchive::getStatusString
返回压缩时的状态内容,包括错误信息,压缩信息等等
8.ZipArchive::deleteIndex
删除压缩包中的某一个文件,如:deleteIndex(0)删除第一个文件
9.ZipArchive::deleteName
删除压缩包中的某一个文件名称,同时也将文件删除。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/825095.htmlTechArticle用ZipArchive压缩文件,这个是php的扩展类,自php5.2版本以后就已经支持这个扩展,如果你在使用的时候出现错误,查看下php.ini里面的extensi...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Best Guide to Compressing HTML Files to ZIP Best Guide to Compressing HTML Files to ZIP Apr 09, 2024 pm 04:09 PM

Compressing HTML files into ZIP can improve page loading speed. Methods include: using online tools (such as FileOptimizer, TinyPNG) using command line tools (such as gzip, 7-zip) using Node.js scripts (using the zlib module)

How to use linux compression zip command How to use linux compression zip command Oct 08, 2023 pm 01:25 PM

The zip command is a very useful compression tool in Linux systems. By using the zip command, you can easily compress files and directories into a zip file and save storage space and facilitate transfer. The basic syntax of the zip command is "zip [options] [compressed file name] [file or directory to be compressed]".

Detailed explanation of decompression file command (zip) under centos7 Detailed explanation of decompression file command (zip) under centos7 Jan 07, 2024 pm 06:30 PM

1. The compressed folder is a zip file [root@cgls]#zip-rmydata.zipmydata2. Unzip mydata.zip into the mydatabak directory [root@cgls]#unzipmydata.zip-dmydatabak3.mydata01 folder and mydata02.txt are compressed into mydata.zip[root@cgls]#zipmydata.zipmydata01mydata02.txt4. Decompress the mydata.zip file directly [root@cgls]#unzipmydata.zip5. View myd

Which one is lossless, 7z or zip? Which one is lossless, 7z or zip? Jan 19, 2021 pm 06:37 PM

7z and zip are both lossless compressions. 7z is a mainstream and efficient compression format with a very high compression ratio; the ZIP file format is a file format for data compression and document storage. 7z has a higher compression ratio, followed by zip; the zip format is more common and has a wide range of technologies, and the windows operating system supports the zip format by default.

How to use Zip function in Java for file compression How to use Zip function in Java for file compression Jun 26, 2023 pm 02:10 PM

Compressing files is a common operation that can save disk space and network transmission time, and Java provides the Zip function for file compression. This article will show how to use the Zip function in Java for file compression through a detailed introduction and example demonstration. 1. Introduction to the Zip function The Zip function is a compression and packaging tool library provided in Java. This function can be used to compress files or folders into a Zip format file. ZipOutputStr is mainly used in the Zip function

Easily master the secrets of ZIP compression of HTML files Easily master the secrets of ZIP compression of HTML files Apr 09, 2024 pm 05:36 PM

HTML file ZIP compression can be achieved through Python's zipfile module: Create a ZIP file object. Add HTML files to the ZIP file. Close the ZIP file object.

How to parse zip archives and obtain file contents in Java How to parse zip archives and obtain file contents in Java May 18, 2023 am 11:34 AM

The function description page uploads a source code compressed package, and the backend decompresses the compressed package and obtains the contents of each file. Related source code (1) First define an entity class corresponding to the decompressed file. packagecom.sonar.data.vo;importlombok.Data;/***File parsing object**@authorYuanqiang.Zhang*@since2022/7/12*/@DatapublicclassUnzipFileVo{/***Type: 0-folder;1- File*/privateIntegertype;/***File path (such as: src/main/java/co

What does zip mean in win8 system? What does zip mean in win8 system? Jul 18, 2023 pm 03:01 PM

The win8 system often needs to compress and decompress files, which is often encountered in daily life. In the past, everyone had to download a decompression tool first, and zip is one of the decompression formats. Today I will tell you in detail about the win8 system. What does zip mean? What does zip mean in win8 system: A long time ago, Microsoft integrated Zip compression support into Windows systems. Customers can compress or decompress files in Zip format without installing third-party compression tools. 1. The first thing is to reduce the files. We often sort out a type of related files together. At this time, packing them into a package will make it easier to manage and the volume will be reduced. Select the file you want to package, or it can be several files.

See all articles