How To Zip File In Php

Zipping files is a common operation in web applications, as it allows you to compress large files or multiple files into a single compressed archive. This can be useful for saving storage space, improving upload and download speeds, or even organizing related files. In this blog post, we will explore how to create a zip archive and add files to it using PHP.

Creating a Zip Archive

PHP provides a built-in class called ZipArchive that makes it easy to create and manage zip archives. To create a new zip archive, you first need to instantiate a new ZipArchive object, and then call the open() method with the desired archive filename and the ZipArchive::CREATE flag.

Here’s an example:

    $zip = new ZipArchive();
    $filename = "my_archive.zip";

    if ($zip->open($filename, ZipArchive::CREATE) !== TRUE) {
        exit("Cannot create the zip archive: $filename\n");
    }
    

Adding Files to the Zip Archive

To add files to the zip archive, you can use the addFile() method. This method takes two arguments: the path of the file you want to add to the archive, and an optional second argument that specifies the local name for the file inside the archive. If the second argument is not provided, the file will be added to the archive with its original name.

Here’s an example of adding a file to the zip archive:

    $fileToAdd = "example.txt";
    $zip->addFile($fileToAdd);
    

If you want to add multiple files to the archive, you can use a loop. For example, let’s say you have an array of file paths that you want to add to the archive:

    $filesToAdd = ['file1.txt', 'file2.txt', 'file3.txt'];

    foreach ($filesToAdd as $file) {
        $zip->addFile($file);
    }
    

Closing the Zip Archive

Once you’ve added all the files you want, you need to close the zip archive by calling the close() method. This will finalize the archive and write it to disk.

Here’s an example:

    $zip->close();
    

Complete Example

Let’s put it all together in a complete example. In this example, we’ll create a zip archive called “my_archive.zip” and add three files to it: “file1.txt”, “file2.txt”, and “file3.txt”.

    $zip = new ZipArchive();
    $filename = "my_archive.zip";

    if ($zip->open($filename, ZipArchive::CREATE) !== TRUE) {
        exit("Cannot create the zip archive: $filename\n");
    }

    $filesToAdd = ['file1.txt', 'file2.txt', 'file3.txt'];

    foreach ($filesToAdd as $file) {
        $zip->addFile($file);
    }

    $zip->close();
    

And that’s it! Now you know how to create a zip archive and add files to it using PHP. You can use this technique in your web applications to compress large files, bundle multiple files together, or even create backups of important data.