DEV Community

Cover image for Create Zip File Using PHP
Asif Sheikh
Asif Sheikh

Posted on

Create Zip File Using PHP

In web development, creating ZIP files dynamically is a common task. For example, you might need to compress multiple files or an entire folder to improve file management, optimize downloads, or serve as backup files. PHP provides an easy way to handle file compression using the ZipArchive class. This article will walk you through the steps to create ZIP files programmatically using PHP.

What is ZipArchive in PHP?

The ZipArchive class is a built-in PHP class that allows you to create, read, and extract ZIP archives. It provides a simple interface for manipulating ZIP files directly from within your PHP scripts.

Requirements

  1. PHP 5.2.0 or later: ZipArchive is available in PHP versions 5.2.0 and above.
  2. PHP ZIP Extension: Ensure the PHP ZIP extension is enabled on your server. If you're using a local development environment, it might need to be enabled manually in your php.ini file.

Step-by-Step Guide to Create a ZIP File

Step 1: Creating the ZIP File
To create a ZIP file, first instantiate the ZipArchive class and specify the name of the ZIP file you want to create.

<?php
// Create a new instance of ZipArchive
$zip = new ZipArchive();

// Specify the name of the ZIP file
$zipFileName = 'my_archive.zip';

// Open the ZIP file for writing. If the file doesn't exist, it will be created
if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
    echo 'ZIP file created successfully!';
} else {
    echo 'Failed to create the ZIP file.';
}
?>
Enter fullscreen mode Exit fullscreen mode

Step 2: Adding Files to the ZIP
After opening the ZIP file, you can add files to it using the addFile() method.

<?php
if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
    // Add files to the ZIP archive
    $zip->addFile('file1.txt', 'file1.txt');  // Add file1.txt to the root of the archive
    $zip->addFile('file2.jpg', 'file2.jpg');  // Add file2.jpg to the root of the archive

    // Close the ZIP file
    $zip->close();
    echo 'Files added to ZIP file!';
} else {
    echo 'Failed to create the ZIP file.';
}
?>
Enter fullscreen mode Exit fullscreen mode

Conclusion

PHP's ZipArchive class offers an easy and flexible way to create and manage ZIP archives. Whether you're compressing files for download, backing up directories, or optimizing storage, this class provides a straightforward solution. By following the steps outlined in this guide, you can effectively create ZIP files from both individual files and entire directories with ease.

Thanks for read this article.😊🥰
If you have any queries related to this article, please🙏 drop query in this comment section. We will reply as soon as possible on your query.

Top comments (0)