Tuesday, December 17, 2013

How to made/create a zip file using php.

class FlxZipArchive extends ZipArchive
{

/**
* Add a Dir with Files and Subdirs to the archive
*
* @param string $location Real Location
* @param string $name Name in Archive
* */
public function addDir($location, $name)
{
$this->addEmptyDir($name);
$this->addDirDo($location, $name);
}

/**
* Add Files & Dirs to archive.
*
* @param string $location Real Location
* @param string $name Name in Archive
* */
private function addDirDo($location, $name)
{
$name .= '/';
$location .= '/';

// Read all Files in Dir
$dir = opendir($location);
while ($file = readdir($dir)) {
if ($file == '.' || $file == '..')
continue;

// Rekursiv, If dir: FlxZipArchive::addDir(), else ::File();
$do = (filetype($location . $file) == 'dir') ? 'addDir' : 'addFile';
$this->$do($location . $file, $name . $file);
}
}

}

function create_zip($archive_folder, $archive_name){

    @unlink($archive_name);

    $za = new FlxZipArchive;

    $res = $za->open($archive_name, ZipArchive::CREATE);
    
    if($res === TRUE) {
    $za->addDir($archive_folder, basename($archive_folder));
    $za->close();
    }
    else
    echo 'Could not create a zip archive';
}//end of function


//now call the function where ever you want
$archive_folder="";//enter folder name here
$archive_name="";//enter name of zip file you want to create here
create_zip($archive_folder,$archive_name);

Feel free to comment ,if it works for you.Thanks!!

No comments:

Post a Comment