Tuesday, 14 August 2018

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";
}

?>

0 comments:

Post a Comment