Wednesday, October 3, 2012

How to create zip and download


In this post I am going to explain you how to create zip file and download.
We need some files on some directory which we will zipped by code.
For this task we are using PHP zip library, it must enabled on your server.
Here is function
function zipFilesDownload($file_names,$archive_file_name,$file_path)

{

    $zip = new ZipArchive();

    //create the file and throw the error if unsuccessful

    if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {

                    exit("cannot open <$archive_file_name>\n");

    }

    //add each files of $file_name array to archive

    foreach($file_names as $files)

    {

                    $zip->addFile($file_path.$files,$files);

                    //echo $file_path.$files,$files."<br />";

    }

    $zip->close();

    //then send the headers to force download the zip file

    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;

}
There are three parameters in function  $file_names, $archive_file_name and $file_path
$file_names =>  where you have to passed files in array.
$archive_file_name => It is the name of your zip file which is created by PHP library if it’s not open.
$file_path =>  It is your directory path where your files are placed which you want to zipped.

No comments:

Post a Comment