Skip to content

PHP: Create Zip files

In PHP, creating zip files is straightforward using the ZipArchive class, which is part of the PHP standard library. Here’s an example of how you can create a zip file:

Users must enable “php_zip.dll” inside of “php.ini” for these functions to work.

<?php
$zip = new ZipArchive();

$zipFileName = 'example.zip';
if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE) {
    // Add files to the zip
    $zip->addFile('file1.txt', 'file1.txt'); // Add a single file
    $zip->addFile('images/image1.jpg', 'images/image1.jpg'); // Add a file from a directory

    // You can also add entire directories recursively
    // $zip->addGlob('path/to/directory/*'); // Add all files in a directory

    $zip->close();
    echo "Zip file created successfully!";
} else {
    echo "Failed to create zip file!";
}
?>

This PHP script uses ZipArchive::open to create a new zip file named example.zip and adds file1.txt and images/image1.jpg to it. You can add files individually or use addGlob to add all files in a directory recursively.

Ensure that you have appropriate permissions to write files in the directory where you are creating the zip file. Adjust the paths and filenames in the addFile and addGlob methods to match your file structure.

Also, handle errors appropriately based on your application’s needs. The ZipArchive::open method returns TRUE upon successful creation and opening of the zip file and FALSE otherwise.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments