Create zip file in PHP

0
665
Create zip file in PHP
Create zip file in PHP

Wonder how to compress files in PHP? I will show you how to create zip file in PHP in this post.

To create zip file in PHP, we will use the ZipArchive class.

There are four steps to create a zip archive:

  1. Create an instance of ZipArchive.
  2. Open the output writer for the zip.
  3. Add files to the zip.
  4. Close the writer to finalize the zip file.

This is sample code that demonstrates how all above steps:

$output = 'compressed.zip';

// Step 1: create an instance
$zip = new ZipArchive();

// Step 2: open zip output writer
$status = $zip->open($output, ZipArchive::CREATE);

if ($status === TRUE) {
    // Step 3: add files to the zip
    $zip->addFile('sample.txt');
    $zip->addFromString('string.txt', 'this is the content');
    $zip->addFromString('sub/inside.txt', 'this file is located under sub directory');

    // Step 4: finalize the zip
    $zip->close();
    echo "Zip file '$output' has been created successfully!";
} else {
    echo "Error creating zip archive!\n";
}

You can add file to the zip archive by passing the complete file path as parameter for addFile().

You can also transform a text into a file inside the zip archive by using addFromString() method. The first parameter is to determine the path where the file should be put into the zip archive.

If you run the above script, you should see the compressed.zip generated in the directory where the script is executed. Extract the content, it should have this structure:

.
|── sample.txt
|── string.txt
|── sub
  └── inside.txt

That’s how you create zip file in PHP.

Have fun!