Extract files from a .zip file using PHP

By: David Sklar Emailed: 1586 times Printed: 2038 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The unzip.php sample program below, extracts files from a ZIP archive. It uses the pc_mkdir_parents() function. The program also requires PHP's zip extension to be installed. You can find documentation on the zip extension at http://www.php.net/zip.

This program takes a few arguments on the command line. The first is the name of the ZIP archive it should unzip. By default, it unzips all files in the archive. If additional command-line arguments are supplied, it only unzips files whose name matches any of those arguments. The full path of the file inside the ZIP archive must be given. If turtles.html is in the ZIP archive inside the animals directory, unzip.php must be passed animals/turtles.html, not just turtles.html, to unzip the file.

Directories are stored as 0-byte files inside ZIP archives, so unzip.php doesn't try to create them. Instead, before it creates any other file, it uses pc_mkdir_parents( ) to create all directories that are parents of that file, if necessary. For example, say unzip.php sees these entries in the ZIP archive:

animals (0 bytes)
animals/frogs/ribbit.html (2123 bytes)
animals/turtles.html   (1232 bytes)

It ignores animals because it is 0 bytes long. Then it calls pc_mkdir_parents() on animals/frogs, creating both animals and animals/frogs, and writes ribbit.html into animals/frogs. Since animals already exists when it reaches animals/turtles.html, it writes out turtles.html without creating any additional directories.

unzip.php (sample code)
// the first argument is the zip file
$in_file = $_SERVER['argv'][1];

// any other arguments are specific files in the archive to unzip
if ($_SERVER['argc'] > 2) {
    $all_files = 0;
    for ($i = 2; $i < $_SERVER['argc']; $i++) {
        $out_files[$_SERVER['argv'][$i]] = true;
    }
} else {
    // if no other files are specified, unzip all files
    $all_files = true;
}

$z = zip_open($in_file) or die("can't open $in_file: $php_errormsg");
while ($entry = zip_read($z)) {
    
    $entry_name = zip_entry_name($entry);

    // check if all files should be unzipped, or the name of
    // this file is on the list of specific files to unzip
    if ($all_files || $out_files[$entry_name]) {

        // only proceed if the file is not 0 bytes long
        if (zip_entry_filesize($entry)) {
            $dir = dirname($entry_name);

            // make all necessary directories in the file's path
            if (! is_dir($dir)) { pc_mkdir_parents($dir); }

            $file = basename($entry_name);

            if (zip_entry_open($z,$entry)) {
                if ($fh = fopen($dir.'/'.$file,'w')) {
                    // write the entire file
                    fwrite($fh,
                           zip_entry_read($entry,zip_entry_filesize($entry)))
                        or error_log("can't write: $php_errormsg");
                    fclose($fh) or error_log("can't close: $php_errormsg");
                } else {
                    error_log("can't open $dir/$file: $php_errormsg");
                }
                zip_entry_close($entry);
            } else {
                error_log("can't open entry $entry_name: $php_errormsg");
            }
        }
    }
}

PHP Home | All PHP Tutorials | Latest PHP Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(3)


1. View Comment

Thank you for this useful script! It works very well, I'm using for backing up my website.
Is it possibile with this script to output the unzip status in realtime? Something like applying ajax to get the output of the file being extracted in real time?


View Tutorial          By: Giuseppe at 2010-12-09 05:35:43
2. View Comment

Thank you for this useful script!

View Tutorial          By: opencart module at 2011-01-03 21:21:37
3. View Comment

Awesome script. works like a charm.

Thank you so much!


View Tutorial          By: blestab at 2011-03-02 04:32:35

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by David Sklar
Find Difference between two dates in PHP
Reading .CSV file in PHP
Appending One Array to Another in PHP
Removing Duplicate Elements from an Array in PHP
Sorting an Array in PHP
Iterating Through an Array in PHP
Password protecting a page in PHP
Deleting Cookies in PHP
Reading Cookie Values in PHP
Setting cookies in PHP
Encrypting and decrypting in PHP
GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP
Using Text-File Databases in PHP
Upload and Download files with FTP in PHP
Extract files from a .zip file using PHP

More Tutorials in PHP
PHP code to import from CSV file to MySQL
PHP code to write to a CSV file from MySQL query
PHP code to write to a CSV file for Microsoft Applications
Convert XML to CSV in PHP
Password must include both numeric and alphabetic characters - Magento
PHP file upload (Large Files)
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Error: Length parameter must be greater than 0
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Handling file locks in PHP
HTML table output using Nested for loops in PHP
Count occurrences of a character in a String in PHP

More Latest News
Most Viewed Articles (in PHP )
Different versions of PHP - History and evolution of PHP
Reading and Writing .gz files in PHP
A Basic Example using PHP in AWS (Amazon Web Services)
Static Methods in PHP
Handling BLOB in PHP and MySQL
preg_match(), function preg_match_all(), preg_grep() in PHP
preg_split() and explode() in PHP
Upload and Download files with FTP in PHP
Anonymous functions as properties in Classes in PHP
Count occurrences of a character in a String in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Traversing Arrays Using list() and each() in PHP
Binary Operators in PHP
do...while Loops in PHP
The new keyword and constructors in PHP
Most Emailed Articles (in PHP)
Integers and Floating-Point Numbers in PHP
Appending One Array to Another in PHP
Reading .CSV file in PHP
Handling BLOB in PHP and MySQL
File Handling in PHP
Upload and Download files with FTP in PHP
Perl's Encoding::FixLatin equivalent in PHP
History and origin of PHP
Variables in PHP
Strings in PHP
switch Statements in PHP
do...while Loops in PHP
Input Validation in PHP
Using Sessions in PHP
Locking files in PHP