Extract the Content of Zip file Using PHP

4 comments
Sometimes you may want the users on your site to upload the zip file and then check what are the contents of that zip file. In this article I will tell you how to extract the contents of the zip file. I temporarily extract the zip files to a directory and then delete it afterwards. You can chose to keep the extracted content if you want. See the live demo here.

Live Demo Download Script
The main function for extracting the zip contents is as follows:
<?php
//Function to extract the contents from zip file
    function extract_zip ($file, $dir) {
        $zip = new ZipArchive;
        $res = $zip->open($file['tmp_name']);
        if ($res === TRUE) {
            $zip->extractTo($dir . '/');
            $zip->close();
            return true;
        } else {
            return false;
        }
    }
?>

Complete Code

<html>
<head>
    <title>Unzip the zip file using PHP | WebSpeaks.in</title>
</head>
<body>
    <?php
    //Array to store the errors
    $errors = array();

    //If form is posted
    if (isset($_POST) && !empty($_POST)) {
        $extract_dir = 'temp';    //directory where file contents are extracted
        $zip_file = $_FILES['file'];
        if ($zip_file['error'] == 1) {
            $errors[] = ' The uploaded file exceeds the maximum upload limit.';
        } else if ($zip_file['error'] == 2) {
            $errors[] = ' The uploaded file exceeds the maximum upload limit.';
        } else if ($zip_file['error'] > 2) {
            $errors[] = ' Some error occurred during upload. Please try again.';
        }

        $temp_dir = $extract_dir . '/' . uniqid('temp_');
        if ($zip_file['error'] < 1 ) {
            if ( $zip_file['type'] == 'application/x-zip-compressed' || $zip_file['type'] == 'application/zip') {
                if (extract_zip($zip_file, $temp_dir) !== FALSE) {
                    $child_files = scan_dir($temp_dir);    //Get all files in the extracted directory
                } else {
                    $errors[] = 'Unable to open the file. Please try again.';
                }
            } else {
                $errors[] = 'This is not a valid zip file.';
            }
        }
        //Remove the temporary directory if files are no further needed
        recursive_remove_directory($temp_dir);
    }

    //Function to scan the directory contents
    function scan_dir ($dir) {
        $files = array();
        $scan = scandir($dir);  
        for ($i=0; $i<count($scan); $i++) {
            if ($scan[$i] != '.' && $scan[$i] != '..') {
                $files[] =     $scan[$i];
            }  
        }
        return $files;
    }

    //Function to extract the contents from zip file
    function extract_zip ($file, $dir) {
        $zip = new ZipArchive;
        $res = $zip->open($file['tmp_name']);
        if ($res === TRUE) {
            $zip->extractTo($dir . '/');
            $zip->close();
            return true;
        } else {
            return false;
        }
    }

    //Function to show the file icon
    function get_icon ($file_name) {
        $icons = array(
                    'avi' => 'avi',
                    'c' => 'c',
                    'cpp' => 'cpp',
                    'css' => 'css',
                    'doc' => 'doc',
                    'flv' => 'flv',
                    'gif' => 'gif',
                    'gz' => 'gz',
                    'htm' => 'htm',
                    'html' => 'html',
                    'jpg' => 'jpg',
                    'mid' => 'mid',
                    'mp3' => 'mp3',
                    'mpg' => 'mpg',
                    'odb' => 'odb',
                    'odc' => 'odc',
                    'odf' => 'odf',
                    'odg' => 'odg',
                    'odi' => 'odi',
                    'odm' => 'odm',
                    'odp' => 'odp',
                    'odt' => 'odt',
                    'otc' => 'otc',
                    'otf' => 'otf',
                    'otg' => 'otg',
                    'oth' => 'oth',
                    'pdf' => 'pdf',
                    'php' => 'php',
                    'png' => 'png',
                    'ppt' => 'ppt',
                    'svg' => 'svg',
                    'swf' => 'swf',
                    'txt' => 'txt',
                    'vsd' => 'vsd',
                    'xhtml' => 'xhtml',
                    'xls' => 'xls',
                    'zip' => 'zip',
                );

        $file_ext = get_file_extension($file_name);
        $img = '<img src="icons/default.png" class="icon" />';
        if(in_array($file_ext, $icons)){
            $img = '<img src="icons/'.$icons[$file_ext].'.png" class="icon" />';
        }
        return $img;
    }

    //Function to get the file extension
    function get_file_extension($file_name) {
        return substr(strrchr($file_name,'.'),1);
    }

    # recursively remove a directory
    function recursive_remove_directory($directory, $empty=FALSE) {
        if (substr($directory,-1) == '/') {
            $directory = substr($directory,0,-1);
        }
        if(!file_exists($directory) || !is_dir($directory)) {
            return FALSE;
        }elseif(is_readable($directory)) {
            $handle = opendir($directory);
            while (FALSE !== ($item = readdir($handle))) {
                if($item != '.' && $item != '..') {
                    $path = $directory.'/'.$item;
                    if(is_dir($path)) {
                        recursive_remove_directory($path);
                    }else{
                        unlink($path);
                    }
                }
            }
            closedir($handle);
            if($empty == FALSE) {
                if(!rmdir($directory)){
                    return FALSE;
                }
            }
        }
        return TRUE;
    }
    ?> 
    <div id="main">
        <form action="" method="POST" enctype="multipart/form-data">
            <table border="1" style="border-collapse:collapse; border:#ccc 1px solid;">
                <?php
                    if (isset($errors) && !empty($errors)) {
                        echo '<tr><th colspan="2">Error</th></tr>';
                        echo '<tr><td colspan="2">';
                        echo '<ul class="error">';
                        foreach ($errors as $error) {
                            echo '<li>'. $error.'</li>';
                        }
                        echo '</ul>';
                        echo '</td></tr>';
                    }
                    if (isset($child_files) && !empty($child_files)) {
                        echo '<tr><th colspan="2">Following files have been extracted</th></tr>';
                        echo '<tr><td colspan="2">';
                        echo '<ul>';
                        foreach ($child_files as $child) {
                            echo '<li>'.get_icon($child) . $child.'</li>';
                        }
                        echo '</ul>';
                        echo '</td></tr>';
                    }
                ?>
                <tr>
                    <td>Choose ZIP File</td>
                    <td><input type="file" name="file" /></td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <input type="submit" value="Unzip" name="submit" class="button" />
                    </td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>

CSS Code

#main{
        width:500px;
        font-family: Georgia, Times, serif;
        color: #444;
        margin:auto;
    }
    table {
        border: 1px double #cccccc;
        padding:5px;
        width:500px;
    }
    th {
        text-align: left;
        padding-left:7px;
    }
    td {
        border: 1px double #cccccc;
        padding:7px;
    }
    ul{
        list-style-type:none;
        padding-left:0px;
    }
    li{
        border-bottom:1px dotted #666666;
        padding-bottom:5px;
        padding-top:5px;
    }
    ul.error{
        color:#CC0033;
    }
    .icon{
        padding: 0 3px 3px;
        vertical-align: middle;
    }
    .button {
        display: inline-block;
        outline: none;
        cursor: pointer;
        text-align: center;
        text-decoration: none;
        padding: .5em 2em .55em;
        -webkit-border-radius: .5em; 
        -moz-border-radius: .5em;
        border-radius: .5em;
        box-shadow: 0 1px 2px rgba(0,0,0,.2);
        background-color:#58B9EB;
        color:#fff;
    }

4 comments

Hey there!

Your live demo doesn't work. Every zip seems to be invalid.

@Pawel you are right.
BTW I use if ( $zip_file['type'] == 'application/x-zip-compressed') check to find the file type. I dont know why most of zip files fail this test. Its really strange for me also.

@Arvind

Yeah, in my opinion it should be:

if ($zip_file['type'] == 'application/x-zip-compressed' || $zip_file['type'] == 'application/zip')

However, I can't find MIME type application/x-zip-compressed on IANA's official list (http://www.iana.org/assignments/media-types/application/index.html)

@Pawel, 'application/x-zip-compressed' is a MIME type, I just checked types of few zip files and it exists there. ALthough I have updated the code and demo with 'application/zip' type also.

We would love to hear from you...

back to top