Generate ZIP file using php


 
Following post will helps you to create a ZIP file using PHP.

We can zip more than one file, Following script will help you to generate zip file and download zip file

<?php

$arr = array("jainish.png","jainish1.png");

if(extension_loaded('zip'))
{
    // Checking ZIP extension is available
    
    $zip = new ZipArchive(); // Load zip library
    
    $zip_name = "jainish-".time().".zip"; // Zip name
    
    if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
    {
        // Opening zip file to load files
        $error .= "* Sorry ZIP creation failed at this time";
    }

    $i=1;
    
    foreach($arr as $file)
    {
        $zip->addFile($file,$i."-".basename($file)); // Adding files into zip
        $i++;
    }
    
    $zip->close();
    
    if(file_exists($zip_name))
    {
        // push to download the zip
        header('Content-type: application/zip');
        header('Content-Disposition: attachment; filename="'.$zip_name.'"');
        readfile($zip_name);
        // remove zip file is exists in temp path
        unlink($zip_name);
    }
    
}else{
    $error .= "* You dont have ZIP extension";
}

?>

If you have any queries, please do not hesitate to contact me at Jainish Senjaliya

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s