How to Zip and Unzip Files in PHP

09/05/2021

Contents

In this article, you will learn how to zip and unzip files in PHP.

The ZipArchive class

In PHP, you can zip and unzip files using the ZipArchive class.

The ZipArchive class is part of the PHP standard library and provides an easy-to-use interface for working with Zip archives.

Zip a file

Here’s an example of how to zip a file:

<?php
  $zip = new ZipArchive;
  $zipName = 'file.zip';

  if ($zip->open($zipName, ZipArchive::CREATE) === TRUE) {
    $zip->addFile('example.txt');
    $zip->close();
    echo 'File zipped successfully!';
  } else {
    echo 'Failed to zip the file';
  }
?>

In this example of zipping a file, we first create an instance of the ZipArchive class and assign it to a variable named $zip. Then, we use the open method of the ZipArchive class to open a new zip archive named file.zip in write mode (ZipArchive::CREATE). If the open method returns TRUE, it means that the archive was opened successfully, and we can then add files to it using the addFile method. Finally, we close the archive using the close method.

Unzip a file

And here’s an example of how to unzip a file:

<?php
  $zip = new ZipArchive;
  $zipName = 'file.zip';

  if ($zip->open($zipName) === TRUE) {
    $zip->extractTo('destination_folder/');
    $zip->close();
    echo 'File unzipped successfully!';
  } else {
    echo 'Failed to unzip the file';
  }
?>

In the example of unzipping a file, we follow the same steps, but instead of creating a new archive, we open an existing archive using the open method in read mode. If the open method returns TRUE, it means that the archive was opened successfully, and we can then extract its contents to a destination folder using the extractTo method. Finally, we close the archive using the close method.

Note that the ZipArchive class also provides other methods for working with Zip archives, such as adding a directory, adding a file with a different name, and so on. You can find more information about the ZipArchive class and its methods in the official PHP documentation:
https://www.php.net/manual/en/class.ziparchive.php