How To Create Zip File Using PHP

Creating zip files using PHP is a simple task. In order to create zip files using PHP, we use the ZipArchive class. In this article we will see how to create zip file from different files which can be in different folders too.

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

The code is written in two files; index.php where the user uploads 2 files of jpeg and png image types which are compressd in the zip file and zip.php where the files are uploaded and zip file created and saved.

index.php – Uploading Files

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

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

    <label>Upload file 2</label> 
    <input name="file2" 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>

CreateZip function


// $files is the array having the file names. For instance, $files = array("file1.txt", "file2.pdf"); // $zip_name is the name of the zip file. For instance $zip="archive.zip"; function createZip($files = array(),$zip_name = '') { //create the archive $zip = new ZipArchive(); if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE) { echo "<p style='color:red;'>Sorry ZIP creation failed at this time</p>"; return false; } //add the files foreach($files as $file) { $zip->addFile($file); } //close the zip -- done! $zip->close(); //check to make sure the file exists return file_exists($zip_name); }

Explanation of code

  • User uploads two files (Full code is given below). These files are uploaded in the files folder.
  • Zip file is created in another folder named zips.
  • The file names are stored in the $files array used in zip.php shown below and the zip file name and location is specified in the $zipFile variable.
  • These variables are passed to the createZip() function to the variables $files and $zip_name respectively.
  • Inside the function, a ZipArchive type of object is created.
  • $zip->open()opens a file with filename as archive.zip inside the zips folder so that we can add files to it. The flag ZipArchive::CREATE specifies that we want to create a new zip file.
  • All the files in the $files array are added to the zip file.
  • $zip->close() closes and saves the changes to the zip file.

zip.php – Processing Uploaded Files And Creating Zip file

<?php

/********* function to create a compressed zip file ********/
function createZip($files = array(),$zip_name = '') {

        //create the archive
        $zip = new ZipArchive();

        if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
        {
            echo "<p style='color:red;'>Sorry ZIP creation failed at this time</p>";
            return false;
        }

        //add the files
        foreach($files as $file) {
            $zip->addFile($file);
        }

        //close the zip -- done!
        $zip->close();

        //check to make sure the file exists
        return file_exists($zip_name);

}

    /**********checking if files uploaded properly**************/
    if(isset($_FILES['file1']['name']) && isset($_FILES['file2']['name'])){

        $file1_name = $_FILES['file1']['name'];
        $file2_name = $_FILES['file2']['name'];
        if($file1_name=="" || $file2_name==""){
            echo "<p style='color:red;font-size:15px;'>Fill in all the fields</p>";
        }
        else{

            $ext1 = strtolower(pathinfo($file1_name, PATHINFO_EXTENSION));
            $ext2 = strtolower(pathinfo($file2_name, PATHINFO_EXTENSION));
            if($_FILES["file1"]["size"]>102400 || $_FILES["file2"]["size"]>102400 || ($ext1!='jpg' && $ext1!='jpeg') || $ext2!='png')
                echo "<p style='color:red;font-size:15px;'>Please upload files with specified properties and size.</p>";
            else{
                $tmp1 = $_FILES['file1']['tmp_name'];
                $tmp2 = $_FILES['file2']['tmp_name'];
                $target_dir = "/home/binodbrothers/public_html/tutsheap.com/demos/web/zip/create/files/";
                $target_file1 = $target_dir.basename($file1_name);
                $target_file2 = $target_dir.basename($file2_name);
                if (move_uploaded_file($tmp1, $target_file1) && move_uploaded_file($tmp2, $target_file2)) {

                    /********************* Creating zip file *********************/

                    //Location and name of the files

                    $file1_name = 'files/'.$file1_name;
                    $file2_name = 'files/'.$file2_name;
                    $files = array($file1_name, $file2_name);

                    //Location and name of the zip file to be created
                    $zipFile = 'zips/archive.zip';
                    $output = createZip($files, $zipFile);

                    if($output){
                        echo '<a href="'.$zipFile.'" target="_blank">Click Here</a> to download zip file';
                    }
                    else{
                        echo '<p style="color:red;">Some error occurred. Please try again.</p>';
                    }

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

        }

    }

?>

Some other functinalities for zip files are explained below.

Overwriting A Zip File

The flag ZipArchive::OVERWRITE is used to overwrite the existing zip file. The code remains similar to what has been used earlier.

$zip = new ZipArchive;
if ($zip->open('archive.zip', ZipArchive::OVERWRITE) === TRUE)
{
    // Adding files to the zip file
    $zip->addFile('file1.pdf');
    $zip->addFile('file2.jpg');

    $zip->close();
}

Add Files To Be Inside A Folder

In order to add files inside a folder or multiple folders, folder name is mentioned with the file name in the addFile() function.

$zip = new ZipArchive;
if ($zip->open('archive.zip', ZipArchive::CREATE) === TRUE)
{
    // Add files to the zip file
    $zip->addFile('file1.pdf', 'folder1/file1.pdf');
    $zip->addFile('file2.jpg', 'folder2/file2.jpg');

    $zip->close();
}

Add All The Files In A Folder/Directory

$zip = new ZipArchive;
if ($zip->open('archive.zip', ZipArchive::OVERWRITE) === TRUE)
{
    if ($handle = opendir('folder'))
    {
        // Add all files inside the folder
        while (false !== ($entry = readdir($handle)))
        {
            if ($entry != "." && $entry != ".." && !is_dir('folder/' . $entry))
            {
                $zip->addFile('folder/' . $entry);
            }
        }
        closedir($handle);
    }

    $zip->close();
}
  • $handle is used to open the folder and read all the files in it.
  • . and .. are used to skip any other folders.
  • $entry = readdir($handle) gets names of each file in the folder.

Index Page

Index

Zipping the files

Zipping files

Zipped file contents

Zip contents

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