PHP
downloads | documentation | faq | getting help | mailing lists | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

zip_close> <yp_order
Last updated: Sun, 25 Nov 2007

view this page in

Zip File Functions

Úvod

This extension enables you to transparently read or write ZIP compressed archives and the files inside them.

Požiadavky

PHP 4

The bundled PHP 4 version requires » ZZIPlib, by Guido Draheim, version 0.10.6 or later

PHP 5.2.0 or later

This extension uses the functions of » zlib by Jean-loup Gailly and Mark Adler.

Inštalácia

PHP 4

Note: Zip support before PHP 4.1.0 is experimental.

Warning

Because the PHP 4 zip extension is unmaintained we recommend that the PECL extension is used rather than the bundled one.

Linux systems

In order to use these functions you must compile PHP with zip support by using the --with-zip[=DIR] configure option, where [DIR] is the prefix of the » ZZIPlib library install.

Windows

Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

PHP 5.2.0 and later

Linux systems

In order to use these functions you must compile PHP with zip support by using the --enable-zip configure option.

Windows

Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

Installation via PECL

Dodatočné informácie ako sú nové vydania, downloady, zdrojové súbory, informácie od spracovávateľa, a CHANGELOG, je možné nájsť tu: » http://pecl.php.net/package/zip.

Toto PECL rozšírenie DLL si môžete stiahnúť zo stránky » PHP Download alebo na » http://snaps.php.net/.

V PHP 4 sa toto DLL nachádza v adresári extensions/ v downloade PHP Windows binariek.

Runtime Konfigurácia

Toto rozšírenie nemá žiadne konfiguračné direktívy definované v php.ini.

Typy zdrojov

There are two resource types used in the Zip module. The first one is the Zip directory for the Zip archive, the second Zip Entry for the archive entries.

Preddefinované Konštanty

Konštanty uvedené nižšie sú definované týmto rozšírením a budú dostupné iba keď rozšírenie bolo buď kompilované do PHP alebo dynamicky načítané za behu (runtime).

ZipArchive uses class constants. There is three types of constants, Flags (FL_) errors (ER_) or mode (no prefix).

ZIPARCHIVE::CREATE (integer)
Create the archive if it does not exist.
ZIPARCHIVE::OVERWRITE (integer)
Always start a new archive, this mode will overwrite the file if it already exists.
ZIPARCHIVE::EXCL (integer)
Error if archive already exists.
ZIPARCHIVE::CHECKCONS (integer)
Perform additional consistency checks on the archive, and error if they fail.
ZIPARCHIVE::FL_NOCASE (integer)
Ignore case on name lookup
ZIPARCHIVE::FL_NODIR (integer)
Ignore directory component
ZIPARCHIVE::FL_COMPRESSED (integer)
Read compressed data
ZIPARCHIVE::FL_UNCHANGED (integer)
Use original data, ignoring changes.
ZIPARCHIVE::CM_DEFAULT (integer)
better of deflate or store.
ZIPARCHIVE::CM_STORE (integer)
stored (uncompressed).
ZIPARCHIVE::CM_SHRINK (integer)
shrunk
ZIPARCHIVE::CM_REDUCE_1 (integer)
reduced with factor 1
ZIPARCHIVE::CM_REDUCE_2 (integer)
reduced with factor 2
ZIPARCHIVE::CM_REDUCE_3 (integer)
reduced with factor 3
ZIPARCHIVE::CM_REDUCE_4 (integer)
reduced with factor 4
ZIPARCHIVE::CM_IMPLODE (integer)
imploded
ZIPARCHIVE::CM_DEFLATE (integer)
deflated
ZIPARCHIVE::CM_DEFLATE64 (integer)
deflate64
ZIPARCHIVE::CM_PKWARE_IMPLODE (integer)
PKWARE imploding
ZIPARCHIVE::CM_BZIP2 (integer)
BZIP2 algorithm
ZIPARCHIVE::ER_OK (integer)
No error.
ZIPARCHIVE::ER_MULTIDISK (integer)
Multi-disk zip archives not supported.
ZIPARCHIVE::ER_RENAME (integer)
Renaming temporary file failed.
ZIPARCHIVE::ER_CLOSE (integer)
Closing zip archive failed
ZIPARCHIVE::ER_SEEK (integer)
Seek error
ZIPARCHIVE::ER_READ (integer)
Read error
ZIPARCHIVE::ER_WRITE (integer)
Write error
ZIPARCHIVE::ER_CRC (integer)
CRC error
ZIPARCHIVE::ER_ZIPCLOSED (integer)
Containing zip archive was closed
ZIPARCHIVE::ER_NOENT (integer)
No such file.
ZIPARCHIVE::ER_EXISTS (integer)
File already exists
ZIPARCHIVE::ER_OPEN (integer)
Can't open file
ZIPARCHIVE::ER_TMPOPEN (integer)
Failure to create temporary file.
ZIPARCHIVE::ER_ZLIB (integer)
Zlib error
ZIPARCHIVE::ER_MEMORY (integer)
Memory allocation failure
ZIPARCHIVE::ER_CHANGED (string)
Entry has been changed
ZIPARCHIVE::ER_COMPNOTSUPP (integer)
Compression method not supported.
ZIPARCHIVE::ER_EOF (integer)
Premature EOF
ZIPARCHIVE::ER_INVAL (integer)
Invalid argument
ZIPARCHIVE::ER_NOZIP (integer)
Not a zip archive
ZIPARCHIVE::ER_INTERNAL (integer)
Internal error
ZIPARCHIVE::ER_INCONS (integer)
Zip archive inconsistent
ZIPARCHIVE::ER_REMOVE (integer)
Can't remove file
ZIPARCHIVE::ER_DELETED (integer)
Entry has been deleted

Príklady

Example#1 Create a Zip archive

<?php

$zip 
= new ZipArchive();
$filename "./test112.zip";

if (
$zip->open($filenameZIPARCHIVE::CREATE)!==TRUE) {
    exit(
"cannot open <$filename>\n");
}

$zip->addFromString("testfilephp.txt" time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip->addFromString("testfilephp2.txt" time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip->addFile($thisdir "/too.php","/testfromfile.php");
echo 
"numfiles: " $zip->numFiles "\n";
echo 
"status:" $zip->status "\n";
$zip->close();
?>

Example#2 Dump the archive details and listing

<?php
$za 
= new ZipArchive();

$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
echo 
"numFiles: " $za->numFiles "\n";
echo 
"status: " $za->status  "\n";
echo 
"statusSys: " $za->statusSys "\n";
echo 
"filename: " $za->filename "\n";
echo 
"comment: " $za->comment "\n";

for (
$i=0$i<$za->numFiles;$i++) {
    echo 
"index: $i\n";
    
print_r($za->statIndex($i));
}
echo 
"numFile:" $za->numFiles "\n";
?>

Example#3 Zip stream wrapper, read an OpenOffice meta info

<?php
$reader 
= new XMLReader();

$reader->open('zip://' dirname(__FILE__) . '/test.odt#meta.xml');
$odt_meta = array();
while (
$reader->read()) {
    if (
$reader->nodeType == XMLREADER::ELEMENT) {
        
$elm $reader->name;
    } else {
        if (
$reader->nodeType == XMLREADER::END_ELEMENT && $reader->name == 'office:meta') {
            break;
        }
        if (!
trim($reader->value)) {
            continue;
        }
        
$odt_meta[$elm] = $reader->value;
    }
}
print_r($odt_meta);
?>

This example uses the old API (PHP 4), it opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.

Example#4 Zip Usage Example

<?php

$zip 
zip_open("/tmp/test2.zip");

if (
$zip) {
    while (
$zip_entry zip_read($zip)) {
        echo 
"Name:               " zip_entry_name($zip_entry) . "\n";
        echo 
"Actual Filesize:    " zip_entry_filesize($zip_entry) . "\n";
        echo 
"Compressed Size:    " zip_entry_compressedsize($zip_entry) . "\n";
        echo 
"Compression Method: " zip_entry_compressionmethod($zip_entry) . "\n";

        if (
zip_entry_open($zip$zip_entry"r")) {
            echo 
"File Contents:\n";
            
$buf zip_entry_read($zip_entryzip_entry_filesize($zip_entry));
            echo 
"$buf\n";

            
zip_entry_close($zip_entry);
        }
        echo 
"\n";

    }

    
zip_close($zip);

}
?>

Table of Contents



zip_close> <yp_order
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
Zip
lostdreamer_nl at hotmail dot com
08-Oct-2008 01:22
in regards to the extracting via unzip.lib.php:
Don't forget to also put in the file path.
Otherwise you end up with a lot of files in the wrong folder...

<?php
require_once("zip.lib.php");
require_once(
"unzip.lib.php");

$zip = new SimpleUnzip();
$filename = "myzippedfile.zip";
$entries = $zip->ReadFile($filename);

foreach (
$entries as $entry){
    
$fh = fopen($entry->Path .'/'.$entry->Name, 'w', false);
   
fwrite($fh,$entry->Data);
   
fclose($fh);
}
?>
phillpafford+php at gmail dot com
12-Jun-2008 06:28
You could just use the linux commands

<?php

// Get the date
$date = date("m-d-y");

// Make Zip name
$zipname = "archive/site-script-backup." . $date . ".zip";

// Make a zip file
$cmd = `zip -r $zipname *`;

?>
fgarciarico at gmail dot com
26-May-2008 11:19
Using the same scripts as the last message:

\libraries\zip.lib.php
\libraries\unzip.lib.php

you can also extract all the files included in a zip file. This is my own example:

require_once("zip.lib.php");
require_once("unzip.lib.php");

$zip = new SimpleUnzip();
$filename = "myzippedfile.zip";
$entries = $zip->ReadFile($filename);

foreach ($entries as $entry){
     $fh = fopen($entry->Name, 'w', false);
    fwrite($fh,$entry->Data);
    fclose($fh);
}
cusimar9 at hotmail dot com
13-May-2008 09:06
Just to second the comments above and say that the zipfile class in phpMyAdmin is excellent.

There are 2 files when you download phpMyAdmin:

\libraries\zip.lib.php
\libraries\unzip.lib.php

Here is a small example:

$zip = new zipfile();
$filename = "1.jpg";
$fsize = @filesize($filename);
$fh = fopen($filename, 'rb', false);
$data = fread($fh, $fsize);             
$zip->addFile($data,$filename);

$zipcontents = $zip->file();

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"TheZip.zip\"");
header("Content-length: " . strlen($zipcontents) . "\n\n");

// output data
echo $zipcontents;
rodrigo dot moraes at gmail dot com
29-Jan-2008 07:56
Here's a more simple extended class to add a whole directory recursively, keeping the same structure. It uses SPL.

<?php
class MyZipArchive extends ZipArchive
{
   
/**
     *
     * Adds a directory recursively.
     *
     * @param string $filename The path to the file to add.
     *
     * @param string $localname Local name inside ZIP archive.
     *
     */
   
public function addDir($filename, $localname)
    {
       
$this->addEmptyDir($localname);
       
$iter = new RecursiveDirectoryIterator($filename);

        foreach (
$iter as $fileinfo) {
            if (!
$fileinfo->isFile() && !$fileinfo->isDir()) {
                continue;
            }

           
$method = $fileinfo->isFile() ? 'addFile' : 'addDir';
           
$this->$method($fileinfo->getPathname(), $localname . '/' .
               
$fileinfo->getFilename());
        }
    }
}
?>
mmj48 at gmail dot com
08-Nov-2007 05:39
Heres a function I wrote that will extract a zip file with the same directory structure...

Enjoy:

<?php
function unzip($zipfile)
{
   
$zip = zip_open($zipfile);
    while (
$zip_entry = zip_read($zip))    {
       
zip_entry_open($zip, $zip_entry);
        if (
substr(zip_entry_name($zip_entry), -1) == '/') {
           
$zdir = substr(zip_entry_name($zip_entry), 0, -1);
            if (
file_exists($zdir)) {
               
trigger_error('Directory "<b>' . $zdir . '</b>" exists', E_USER_ERROR);
                return
false;
            }
           
mkdir($zdir);
        }
        else {
           
$name = zip_entry_name($zip_entry);
            if (
file_exists($name)) {
               
trigger_error('File "<b>' . $name . '</b>" exists', E_USER_ERROR);
                return
false;
            }
           
$fopen = fopen($name, "w");
           
fwrite($fopen, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)), zip_entry_filesize($zip_entry));
        }
       
zip_entry_close($zip_entry);
    }
   
zip_close($zip);
    return
true;
}
?>
nheimann at gmx dot net
03-Nov-2007 08:19
With this extension you can Add dirs with files with the ZipArchive Object

/**
 * FlxZipArchive, Extends ZipArchiv.
 * Add Dirs with Files and Subdirs.
 *
 * <code>
 *  $archive = new FlxZipArchive;
 *  // .....
 *  $archive->addDir( 'test/blub', 'blub' );
 * </code>
 */
class FlxZipArchive extends ZipArchive {
    /**
     * Add a Dir with Files and Subdirs to the archive
     *
     * @param string $location Real Location
     * @param string $name Name in Archive
     * @author Nicolas Heimann
     * @access private
     **/

    public function addDir($location, $name) {
        $this->addEmptyDir($name);

        $this->addDirDo($location, $name);
//     } // EO addDir;

    /**
     * Add Files & Dirs to archive.
     *
     * @param string $location Real Location
     * @param string $name Name in Archive
     * @author Nicolas Heimann
     * @access private
     **/

    private function addDirDo($location, $name) {
        $name .= '/';
        $location .= '/';

        // Read all Files in Dir
        $dir = opendir ($location);
        while ($file = readdir($dir))
        {
            if ($file == '.' || $file == '..') continue;

            // Rekursiv, If dir: FlxZipArchive::addDir(), else ::File();
            $do = (filetype() == 'dir') ? 'addDir' : 'addFile';
            $this->$do($location . $file, $name . $file);
        }
    } // EO addDirDo();
}
bushj at rpi dot edu
25-Jun-2007 10:59
I made a zip stream handler in case your distribution does not have the built in one using the new ZipArchive system. This one also features the ability to grab entries by index as well as by name. It is similar in capabilities to the builtin gzip/bzip2 compression stream handlers (http://us2.php.net/manual/en/wrappers.compression.php) except it does not support writing.

To use:
fopen('zip://absolute/path/to/file.zip?entryname', $mode) or
fopen('zip://absolute/path/to/file.zip#entryindex', $mode) or
fopen('zip://absolute/path/to/file.zip', $mode)

$mode can only be 'r' or 'rb'. In the last case the first entry in the zip file is used.

<?php
class ZipStream {
  public
$zip; //the zip file
 
public $entry; //the opened zip entry
 
public $length; //the uncompressed size of the zip entry
 
public $position; //the current position in the zip entry read
  //Opens the zip file then retrieves and opens the entry to stream
 
public function stream_open($path, $mode, $options, &$opened_path) {
    if (
$mode != 'r' && $mode != 'rb') //only accept r and rb modes, no writing!
     
return false;
   
$path = 'file:///'.substr($path, 6); //switch out file:/// for zip:// so we can use url_parse
   
$url = parse_url($path);
   
//open the zip file
   
$filename = $url['path'];
   
$this->zip = zip_open($filename);
    if (!
is_resource($this->zip))
      return
false;

   
//if entry name is given, find that entry   
   
if (array_key_exists('query', $url) && $url['query']) {
     
$path = $url['query'];
      do {
       
$this->entry = zip_read($this->zip);
        if (!
is_resource($this->entry))
          return
false;
      } while (
zip_entry_name($this->entry) != $path);    
    } else {
//otherwise get it by index (default to 0)
     
$id = 0;
      if (
array_key_exists('fragment', $url) && is_int($url['fragment']))
       
$id = $url['fragment']*1;
      for (
$i = 0; $i <= $id; $i++) {
       
$this->entry = zip_read($this->zip);
        if (!
is_resource($this->entry))
          return
false;
      }
    }
   
//setup length and open the entry for reading
   
$this->length = zip_entry_filesize($this->entry);
   
$this->position = 0;
   
zip_entry_open($this->zip, $this->entry, $mode);
    return
true;
  }
 
//Closes the zip entry and file
 
public function stream_close() { @zip_entry_close($this->entry); @zip_close($this->zip); }
 
//Returns how many bytes have been read from the zip entry
 
public function stream_tell() { return $this->position; }
 
//Returns true if the end of the zip entry has been reached
 
public function stream_eof() { return $this->position >= $this->length; }
 
//Returns the stat array, only 'size' is filled in with the uncompressed zip entry size
 
public function url_stat() { return array('dev'=>0, 'ino'=>0, 'mode'=>0, 'nlink'=>0, 'uid'=>0, 'gid'=>0, 'rdev'=>0, 'size'=>$this->length, 'atime'=>0, 'mtime'=>0, 'ctime'=>0, 'blksize'=>0, 'blocks'=>0); }
 
//Reads the next $count bytes or until the end of the zip entry. Returns the data or false if no data was read.
 
public function stream_read($count) {
   
$this->position += $count;
    if (
$this->position > $this->length)
     
$this->position = $this->length;
    return
zip_entry_read($this->entry, $count);
  }
}
//Register the zip stream handler
stream_wrapper_register('zip', 'ZipStream'); //if this fails there is already a zip stream handler and we will just use that one
?>
martinlarsen at bigfoot dot com
07-Jun-2007 04:40
Lennart Poot's example of using phpMyAdmin's zip library is missing the echo that will actually output the final zip file.

At the end (but before the exit which isn't needed anyway), add this line:

echo $dump_buffer;
darkstream777 at gmx dot net
15-May-2007 04:19
Hi,
i modified the function from nielsvandenberge, now you
can also use relative path's, i added also error messages
and another small highlights, have fun.

<?php
/**
 * Unzip the source_file in the destination dir
 *
 * @param   string      The path to the ZIP-file.
 * @param   string      The path where the zipfile should be unpacked, if false the directory of the zip-file is used
 * @param   boolean     Indicates if the files will be unpacked in a directory with the name of the zip-file (true) or not (false) (only if the destination directory is set to false!)
 * @param   boolean     Overwrite existing files (true) or not (false)
 *
 * @return  boolean     Succesful or not
 */
function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
{
  if(
function_exists("zip_open"))
  {  
      if(!
is_resource(zip_open($src_file)))
      {
         
$src_file=dirname($_SERVER['SCRIPT_FILENAME'])."/".$src_file;
      }
     
      if (
is_resource($zip = zip_open($src_file)))
      {         
         
$splitter = ($create_zip_name_dir === true) ? "." : "/";
          if (
$dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";
        
         
// Create the directories to the destination dir if they don't already exist
         
create_dirs($dest_dir);

         
// For every file in the zip-packet
         
while ($zip_entry = zip_read($zip))
          {
           
// Now we're going to create the directories in the destination directories
          
            // If the file is not in the root dir
           
$pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
            if (
$pos_last_slash !== false)
            {
             
// Create the directory where the zip-entry should be saved (with a "/" at the end)
             
create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
            }

           
// Open the entry
           
if (zip_entry_open($zip,$zip_entry,"r"))
            {
            
             
// The name of the file to save on the disk
             
$file_name = $dest_dir.zip_entry_name($zip_entry);
            
             
// Check if the files should be overwritten or not
             
if ($overwrite === true || $overwrite === false && !is_file($file_name))
              {
               
// Get the content of the zip entry
               
$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));          
               
                if(!
is_dir($file_name))           
               
file_put_contents($file_name, $fstream );
               
// Set the rights
               
if(file_exists($file_name))
                {
                   
chmod($file_name, 0777);
                    echo
"<span style=\"color:#1da319;\">file saved: </span>".$file_name."<br />";
                }
                else
                {
                    echo
"<span style=\"color:red;\">file not found: </span>".$file_name."<br />";
                }
              }
            
             
// Close the entry
             
zip_entry_close($zip_entry);
            }     
          }
         
// Close the zip-file
         
zip_close($zip);
      }
      else
      {
        echo
"No Zip Archive Found.";
        return
false;
      }
    
      return
true;
  }
  else
  {
      if(
version_compare(phpversion(), "5.2.0", "<"))
     
$infoVersion="(use PHP 5.2.0 or later)";
     
      echo
"You need to install/enable the php_zip.dll extension $infoVersion";
  }
}

function
create_dirs($path)
{
  if (!
is_dir($path))
  {
   
$directory_path = "";
   
$directories = explode("/",$path);
   
array_pop($directories);
  
    foreach(
$directories as $directory)
    {
     
$directory_path .= $directory."/";
      if (!
is_dir($directory_path))
      {
       
mkdir($directory_path);
       
chmod($directory_path, 0777);
      }
    }
  }
}
?>

greetings darki777
nielsvandenberge at hotmail dot com
11-May-2007 02:29
This is the function I use to unzip a file.
It includes the following options:
* Unzip in any directory you like
* Unzip in the directory of the zip file
* Unzip in a directory with the zipfile's name in the directory of the zip file. (i.e.: C:\test.zip will be unzipped in  C:\test\)
* Overwrite existing files or not
* It creates non existing directories with the function Create_dirs($path)

You should use absolute paths with slashes (/) instead of backslashes (\).
I tested it with PHP 5.2.0 with php_zip.dll extension loaded

<?php
/**
 * Unzip the source_file in the destination dir
 *
 * @param   string      The path to the ZIP-file.
 * @param   string      The path where the zipfile should be unpacked, if false the directory of the zip-file is used
 * @param   boolean     Indicates if the files will be unpacked in a directory with the name of the zip-file (true) or not (false) (only if the destination directory is set to false!)
 * @param   boolean     Overwrite existing files (true) or not (false)
 * 
 * @return  boolean     Succesful or not
 */
function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
{
  if (
$zip = zip_open($src_file))
  {
    if (
$zip)
    {
     
$splitter = ($create_zip_name_dir === true) ? "." : "/";
      if (
$dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";
     
     
// Create the directories to the destination dir if they don't already exist
     
create_dirs($dest_dir);

     
// For every file in the zip-packet
     
while ($zip_entry = zip_read($zip))
      {
       
// Now we're going to create the directories in the destination directories
       
        // If the file is not in the root dir
       
$pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
        if (
$pos_last_slash !== false)
        {
         
// Create the directory where the zip-entry should be saved (with a "/" at the end)
         
create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
        }

       
// Open the entry
       
if (zip_entry_open($zip,$zip_entry,"r"))
        {
         
         
// The name of the file to save on the disk
         
$file_name = $dest_dir.zip_entry_name($zip_entry);
         
         
// Check if the files should be overwritten or not
         
if ($overwrite === true || $overwrite === false && !is_file($file_name))
          {
           
// Get the content of the zip entry
           
$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

           
file_put_contents($file_name, $fstream );
           
// Set the rights
           
chmod($file_name, 0777);
            echo
"save: ".$file_name."<br />";
          }
         
         
// Close the entry
         
zip_entry_close($zip_entry);
        }      
      }
     
// Close the zip-file
     
zip_close($zip);
    }
  }
  else
  {
    return
false;
  }
 
  return
true;
}

/**
 * This function creates recursive directories if it doesn't already exist
 *
 * @param String  The path that should be created
 * 
 * @return  void
 */
function create_dirs($path)
{
  if (!
is_dir($path))
  {
   
$directory_path = "";
   
$directories = explode("/",$path);
   
array_pop($directories);
   
    foreach(
$directories as $directory)
    {
     
$directory_path .= $directory."/";
      if (!
is_dir($directory_path))
      {
       
mkdir($directory_path);
       
chmod($directory_path, 0777);
      }
    }
  }
}

// Extract C:/zipfiletest/zip-file.zip to C:/zipfiletest/zip-file/ and overwrites existing files
unzip("C:/zipfiletest/zip-file.zip", false, true, true);

// Extract C:/zipfiletest/zip-file.zip to C:/another_map/zipfiletest/ and doesn't overwrite existing files. NOTE: It doesn't create a map with the zip-file-name!
unzip("C:/zipfiletest/zip-file.zip", "C:/another_map/zipfiletest/", true, false);

?>
jeswanth@gmail
30-Apr-2007 12:55
Hi, all

There are lot of functions given below which etracts files, but what they lack is setting file permissions. On some servers file permissions are very important and the script cease to work after creating first directory, So I have added chmod to the code. There is only one limitation to the code, files without file extension are neither treated as files or directories so they are not chmoded, anyway this does not affect the code. Hope this helps.

<?php
function unpackZip($dir,$file) {
   if (
$zip = zip_open($dir.$file.".zip")) {
     if (
$zip) {
      
mkdir($dir.$file);
    
chmod($dir.$file, 0777);
       while (
$zip_entry = zip_read($zip)) {
         if (
zip_entry_open($zip,$zip_entry,"r")) {
          
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
          
$dir_name = dirname(zip_entry_name($zip_entry));
           if (
$dir_name != ".") {
            
$dir_op = $dir.$file."/";
               foreach (
explode("/",$dir_name) as $k) {
                
$dir_op = $dir_op . $k;
                 if (
is_file($dir_op)) unlink($dir_op);
                 if (!
is_dir($dir_op)) mkdir($dir_op);
           
chmod($dir_op, 0777);
                
$dir_op = $dir_op . "/" ;
                 }
               }
          
$fp=fopen($dir.$file."/".zip_entry_name($zip_entry),"w+");
       
chmod($dir.$file."/".zip_entry_name($zip_entry), 0777);
          
fwrite($fp,$buf);

          
fclose($fp);

          
zip_entry_close($zip_entry);
       } else
           return
false;
       }
      
zip_close($zip);
     }
  } else
     return
false;

  return
true;
}

$dir = $_SERVER['DOCUMENT_ROOT']."/"."destdirectory/";
$file = 'zipfilename_without_extension';
unpackZip($dir,$file);
$print = $_SERVER['DOCUMENT_ROOT'];
?>
max at centdessin dot com
18-Oct-2006 12:19
I've needed a simple php class to manipulate zip files without PCEL extension, after reading all comment and tested 2 nice classes, here's my conclusion:

"You can use PHPMyAdmin's zip.lib"
-- Lennart Poot -- 12-Jul-2006 07:33

true, getting it is a bit awkward but the class is straight foward and works. BUT it only create zip files, it wont extract them.

"Hey guys, maybe you should check this out:
http://www.phpconcept.net/pclzip/index.en.php "
-- master_auer at web dot de -- 16-Nov-2003 07:49

true, check it if you need more advanced feature, this class is awsome.
bholub at chiefprojects dot com
17-Oct-2006 12:14
This will simply unpack (including directories) $zip to $dir -- in this example the zip is being uploaded.
<?php
    $dir
= 'C:\\reports-temp\\';
   
$zip = zip_open($_FILES['report_zip']['tmp_name']);
    while(
$zip_entry = zip_read($zip)) {
       
$entry = zip_entry_open($zip,$zip_entry);
       
$filename = zip_entry_name($zip_entry);
       
$target_dir = $dir.substr($filename,0,strrpos($filename,'/'));
       
$filesize = zip_entry_filesize($zip_entry);
        if (
is_dir($target_dir) || mkdir($target_dir)) {
            if (
$filesize > 0) {
               
$contents = zip_entry_read($zip_entry, $filesize);
               
file_put_contents($dir.