Friday, 27 May 2016

Create Zip file out of your Folder using PHP

Dear Friends,
Use this code to generate and download zip files. NB: no echo statements should be there in your code. If so should comment it.

//Code starts below


<?php

$file_names=array();

$dir="HUP/";
if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            $file_names = array();
            while (false !== ($file = readdir($handle))) {
                if (is_file($dir.$file) && $file != basename($_SERVER['PHP_SELF'])) $file_names[] = $file;
            }
            closedir($handle);
            if (is_array($file_names)) sort($file_names);
          
        }
    }

$error = "";      //error holder
$file_path="HUP/";
//echo "entered 1";
if(extension_loaded('zip'))
{ // Checking ZIP extension is available
//echo "entered 2";
    if(count($file_names) > 0)
    {  
    //echo "entered 3";
        // Checking files are selected
        $zip = new ZipArchive();            // Load zip library
        $zip_name = 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<br/>";
            //echo $error;
        }
        foreach($file_names as $file){ 

            $zip->addFile($file_path.$file);            // Adding files into zip
        }
        $zip->close(); 
        //echo $zip_name;
        if(file_exists($zip_name))
       {
        //echo "entered 4";
            // 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 .= "* Please select file to zip <br/>";
    }
}
else
{
    $error .= "* You dont have ZIP extension<br/>";
}
?> 

1 comment:

  1. Great sharing. I was surprised how to do it. Thanks for this sharing and it will help us as Zip file extractor app.

    ReplyDelete