An example of ZipArchive class usage for php

  • 2021-07-21 08:06:50
  • OfStack

This article describes the example of php ZipArchive class usage, to share for your reference. The details are as follows:

In general, php 5.2 starts to support the ZipArchive class, and php4 can only use the zip function. In fact, before the official implementation of zip class, Daniel has contributed the method of packaging and decompressing zip files. Now php includes the ZipArchive class, which is of course preferred. Use this class can create and decompress zip files, but also directly read zip compressed package content, very convenient, here mainly summarizes the reading and decompression process.

Unzip 1 package to the specified directory:

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->extractTo('/my/destination/dir/');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

If you only need to read the contents of a file in the package, you need the file name or the index value of the file.

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    echo $zip->getFromName('example.php');
    $zip->close();
}
?>

If example. php is in a directory, you need to add a path to get the content.

If you only know the file name, but don't know the specific path to the file, you can search the index with the specified file name, and then rely on the index to get the content.

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $index=$zip->locateName('example.php', ZIPARCHIVE::FL_NOCASE|ZIPARCHIVE::FL_NODIR);
    $contents = $zip->getFromIndex($index);
}
?>

The index obtained above depends on locateName method. If there are files with the same name under multiple paths in the compressed package, it seems that only the first index can be returned. If you want to obtain the indexes of all files with the same name, you can only use stupid methods and search circularly.

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    for($i = 0; $i < $zip->numFiles; $i++)
      {
           if(substr_count($zip->getNameIndex($i), 'example.php')>0){
                $contents = $zip->getFromIndex($i);                           
            }
       }
}
?>

I hope this article is helpful to everyone's php programming.


Related articles: