How to create and download zip file using PHP

PHP provides simple method to create zip file from the files or simple text files. There is ZipArchive class available for working with zip file. To use this class, first of all you need to download php-zip extension.

sudo apt-get install php7.0-zip

Then, you might have to restart your web server.

sudo service apache2 restart

or

sudo service nginx restart

Now you are ready to zip file.

<?php

$zip = new ZipArchive();

$filename = 'file.zip';

if ($zip->open($filename, ziparchive::CREATE) !== TRUE) {
    exit("cannot open <$filename>\n");
}

$zip->addFromString('file.txt', 'Hi there, it is file.txt'); // add new raw file
$zip->addFile("path-to/file.txt", "/file.php"); // to add current file

// close and save archive
$zip->close();

// download file
if (file_exists($filename)) {
    header('Content-Type: application/zip');
    header('Content-Length: ' . filesize($filename));

    // download zip
    readfile($filename);
    
    // delete after download
    unlink($filename);
}

I hope you would like this article. Follow us on Twitter and like us on Facebook.

Tags: