How to Create a Zip File in PHP

John Wachira Feb 15, 2024
  1. Create a Zip File Using PHP
  2. Unzip the Zip Files Using PHP
How to Create a Zip File in PHP

This tutorial will demonstrate creating a zip file and unzipping that file using PHP, and adding files inside a folder in the zip file.

Create a Zip File Using PHP

The example code below will create a zip file, tutorial.zip, and add files.

In our htdocs directory, we have the Files to zip folder containing two files. We will zip the directory Files to zip.

<?php
// Enter the name of directory
$pathdir = "Files to zip/";

//Create a name for the zip folder
$zipcreated = "Files to zip.zip";

// Create new zip class
$zip = new ZipArchive;

if($zip -> open($zipcreated, ZipArchive::CREATE ) === TRUE) {

    // Store the files in our `Files to zip` zip file.
    $dir = opendir($pathdir);

    while($file = readdir($dir)) {
        if(is_file($pathdir.$file)) {
            $zip -> addFile($pathdir.$file, $file);
}
}
}
?>

This code creates a new zip, Files to zip in our root directory, as shown below.

Files to zip image

We used the directory Files to zip to create the zip folder Files to zip. Our directory had two files, insert.php and Loader.php.

We should find the above files in our zip folder. Let’s take a look.

Inside the zip file

Unzip the Zip Files Using PHP

Let’s look at how you can unzip the zip file with PHP.

Example:

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

// Add zip filename which needs to unzip

$zip->open('Files to zip.zip');

// Extracts to current directory
$zip->extractTo('./Files to zip');

$zip->close();
?>

Output:

Unzip the zip file

We use the code to unzip Files to zip.zip to the Files to zip folder.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - PHP Zip