How to zip and unzip files in PHP

Compressing files when transferring them over the internet has a lot of advantages like it saves time and data transfer. With zip and unzip we can reduce file size and save lots of time while transferring.

PHP comes with a lot of extensions that deal specifically with file compression and extraction. While working in PHP, we don’t require any extra plugins to compress or extract zip files. Using the ZipArchive class, you can simply create a zip file or extract the existing zip file. It has various methods for zip files.

In this tutorial, we will take examples of Zip and Unzip files in PHP.

Unzip Files

To unzip the zip file, we will use the extractTo() method provided by the ZipArchive class. This function takes two parameters which are destination and files. We will use the second parameter when we want to extract specific files.

Let’s take an example to extract all files or specific files.

<?php
    $zip = new ZipArchive;

    if ($zip->open('images.zip') === TRUE) {    //Zip file name
        // To extract all files
        $zip->extractTo('/uploads/images/');    //Destination location

        //To extract specific file
        $zip->extractTo('/uploads/images/', 'file.txt');    //Destination location
        $zip->close();

        echo 'Success';
    } else {
        echo 'Failed';
    }
?>

In the above example, we have created an object of the ZipArchive class, and then we try to open a zip file and print a message according to it. After that, we will use the extractTo() method and pass the destination folder as a parameter. Use a second way to extract specific files. Here, you can pass an array with the names of files or directories.

Create Zip File

We can add files to the zip archive one at a time or add the whole directory at once. In either case, the first step is to create a new ZipArchive instance and then call the open() method.

<?php
    // Create new zip class
    $zip = new ZipArchive;

    if($zip -> open('file.zip', ZipArchive::CREATE ) === TRUE) {

        $dir = opendir('test'); //Directory Name

        //Loop through dir and add files one by one
        while($file = readdir($dir)) {
            if(is_file($pathdir.$file)) {
                $zip -> addFile($pathdir.$file, $file);
            }
        }
        $zip ->close();
    }
?>

In the above example, we created a new ZipArchive class object. Then we opened our directory using the opendir command. For adding files to our zip archive we have to loop through all files of the selected directory and add them one by one. Lastly, the close method will close the ZipArchive object and create a zip file in our file system.

Conclusion

In this article, we have compressed and extracted a zip file in PHP using the ZipArchive class. Now You should be able to compress or extract individual files or a group of them at once as per your requirement.