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


sudo service nginx restart

Now you are ready to zip file.


$zip = new ZipArchive();

$filename = '';

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

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

    // download zip
    // delete after download

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