How Create a Zip File Using PHP

- 2019-05-15 02:03:54

Hello friends now we are going to discus a small code for creating Zip file using PHP. Creating zip file is simple as comparing with author languages.


PHP have a very useful class called ZipArchive ,To create multiple zip files in this post i will show you how create a ZIP file

Source


<?php
function zipFilesDownload($file_names,$archive_file_name,$file_path)
{
    $zip = new ZipArchive();

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

    foreach($file_names as $files)
    {
          $zip->addFile($file_path.$files,$files);
    }
    $zip->close();

    header("Content-type: application/zip");
    header("Content-Disposition: attachment; filename=$archive_file_name");
    header("Pragma: no-cache");
    header("Expires: 0");
    readfile("$archive_file_name");
    exit;
}

$fileNames=array('files/file1.docx','files/file1.pdf');
$zip_file_name='myFile.zip';
$file_path=dirname(__FILE__).'/';
zipFilesDownload($fileNames,$zip_file_name,$file_path);
?>