How to Extract Zip File Using PHP

In this article, you will see how you can extract or unzip zip files in PHP. In order to extract the contents of a zip file in PHP, we use the ZipArchive class.

If you want to see how to create or read zip file, use the links given below.
How to create a zip file using PHP
How to read a zip file using PHP

The code is written in two files; index.php where user uploads the zip file and extract.php where the file are uploaded and extracted and its contents shown.

index.php – Uploading Zip File

<form action="extract.php" method="post" enctype="multipart/form-data">

    <label>Upload zip file</label> 
    <input name="zip" type="file" size="30" required /><br><span>(Max file size : 100Kb)</span><br><br>

    <input name="submit" type="submit" id="submit" class="submit" value="Submit" />

</form>

extractZip Function

//$file is the name and location of the uploaded zip file
//$target is the diectory where file will be extracted

function extractZip($file, $target){

    // Creating new ZipArchive object
    $zip = new ZipArchive();

    // Opening the file
    $open = $zip->open($file);

    //Checking if file has been opened properly
    if($open === true) {

        // Extracting the zip file
        $zip->extractTo($target);

        //Closing the zip file
        $zip->close();

        // Deleting the zip file
        unlink($file);

        return true;
    } 
    else {
        return false;
    }

}

ShowFileContents Function

function showFileContents($target){

    $scan = scandir($target);

    echo  '<ul>';
    for ($i = 0; $i<count($scan); $i++) {
        if(strlen($scan[$i]) >= 3) {
          echo '<li>' . $scan[$i] . '</li>'; 
        }
    }
    print '</ul>';
}

Explanation of Code

  • User uploads the zip file. This file is uploaded in a new directory where the contents of the file will be extracted. (Full code is given below)
  • extractZip function is called and the parameters viz the file name with location and the target directory where files are to be extracted are passed to the function. The variables $file and $target are respectively used for this purpose.
  • Inside the function, a ZipArchive type of object is created.
  • $zip->open()opens the zip file.
  • If the file has been opened properly, then $zip->extractTo($target) is used to extract all the contents inside the zip in the target directory.
  • $zip->close() closes the zip file.
  • unlink($file) deletes the zip file.
  • showFileContents function is used to display all the files inside the target directory.

extract.zip – Extracting zip file

<?php

// Include the two functions explained above here

if(isset($_FILES['zip']['name'])){

        /****************checking file credentials***************/
        $file_name = $_FILES['zip']['name'];
        if($file_name==""){
            echo "<p style='color:red;font-size:15px;'>No file uploaded</p>";
        }
        else{
            $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            if($ext!="zip")
                echo "<p style='color:red;font-size:15px;'>Upload file with zip extension only</p>";
            else{

                if($_FILES["zip"]["size"]>102400)
                    echo "<p style='color:red;font-size:15px;'>Maximum file size allowed is 100Kb.</p>";
                else{
                    $tmp = $_FILES['zip']['tmp_name'];
                    $target = "Your target directory/files/";

                    //Using file name and time to name the new directory
                    $target = $target.basename($file_name,'.zip').'-'.time().'/';
                    // basename($file_name,'.zip') removes extension of the file leaving only the name

                    //Creating the target directory
                    mkdir($target);

                    $target_file = $target.$file_name;

                    if (move_uploaded_file($tmp, $target_file)) {

                        /*******************Extracting zip file********************/
                        $result = extractZip($target_file,$target);

                        if($result){
                            //Successful extraction
                            echo "<p style='color:green;font-size:18px;'>Files extracted</p>";
                            // Show the contents of the directory
                            showFileContents($target);
                        }
                        else{
                            echo "<p style='color:red;font-size:15px;'>There was a problem. Please try again!</p>";
                        }

                    } 
                    else {
                        echo "<p style='color:red;font-size:15px;'>Sorry, there was an error uploading your file.</p>";
                    }
                }

            }
        }

    }
?>

Index Page

Index page

Extracted files

Extracted Files

Original Zip File Contents

zip-file

Please feel free to download the source code for reference.

View Demo Download source

This content has been helpful to you?

Thanks for contributing!

Yes No
  • Pingback: How To Create Zip File Using PHP - Tuts Heap()

  • Patarapol Pothiraj

    Can I specify the extract target to various directories at once?
    and How to code?

    • Vaibhav Goyal

      Yes you can do that. But you must know the specific files inside the zip file which you want to extract to specific directories. If you do not know the files, then you must first read the zip file.

      You can see how to read zip file on this link – http://tutsheap.com/web/how-to-read-zip-file-using-php/

      Use the following code for extracting to specific directories:

      $zip = new ZipArchive;
      $res = $zip->open(‘test.zip’);
      if ($res === TRUE) {
      $zip->extractTo(‘/my/destination/dir/’, array(‘testitem.gif’, ‘testfromfile.php’));
      $zip->close();
      echo ‘ok’;
      } else {
      echo ‘failed’;
      }

      • Patarapol Pothiraj

        Thank you so much. 😀