Tips & Tricks

Create a Zip File Using PHP

I am not sure about other programming language but for PHP yes its quite a simple job to create a zip file. You can say as simple as you create on your machine.

PHP has a very useful class [code]ZipArchive[/code] to create and manipulate the .Zip files. In this post I will show how to create and extract .zip files using PHP.

Here are the function which we will use for this tutorial. [code]open()[/code] for open/create any zip file, [code]addFile()[/code] for adding the files to archieve, [code]close()[/code] for safely close the zip file and [code]extractTo()[/code] for extracting the .zip file.

How to create .zip File using PHP

[cc lang=”php”]
// Creating object of the ZipArchive
$zip = new ZipArchive();

$ow = 1;
$file= “master.zip”;
if($zip->open($file,$ow?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)===TRUE)
{
// Add the files to the .zip file
$zip->addFile(“master.css”);

// This means style.css will be added as new_style.css
$zip->addFile(“style.css”, “new_style.css”);

$zip->addFile(“fonts.css”);

// Closing the zip file
$zip->close();

// Above code will generate master.zip
// containing master.css, new_style.css, fonts.css
}
[/cc]

Extract .zip file using PHP

[cc lang=”php”]

// Creating object of the ZipArchive
$zip = new ZipArchive();

// Open master.zip for extracting all files
if ($zip->open(“master.zip”) === TRUE)
{
// Will extract all files from master.zip to given path.
$zip->extractTo(“/path/to/folder/”);
$zip->close();
}

// Extract only several files

// Open master.zip for extracting single files
if ($zip->open(“master.zip”) === TRUE)
{
// Will extract only fonts.css from master.zip to given path.
$zip->extractTo(“/path/to/folder/”,”fonts.css”);
$zip->close();
}

// Open master.zip for extracting multiple files
if ($zip->open(“master.zip”) === TRUE)
{
// Will extract only fonts.css and master.css
// from master.zip to given path.
$files = array(“fonts.css”,”master.css”);
$zip->extractTo(“/path/to/folder/”,$files);
$zip->close();
}
[/cc]

Shares:
  • […] Source: PHP – Google Blog Search […]

    Reply
  • Name
    Name
    September 14, 2011 at 6:41 am

    I was trying to read and understand this post and I’ve found that it is really that significant and useful to everyone. I have a little knowledge abot some programming language but for PHP yes its quite a simple job to create a zip file. You can say as simple as you create on your machine.

    Reply
  • goldfishcare
    November 22, 2011 at 3:28 pm

    PHP is my favorite language programming, because use web base design, i like it, and your blog give inspiration to my knowledge of PHP , thank you

    Reply
  • singar
    singar
    February 10, 2012 at 11:20 pm

    thanks avinash for your excellent self explanatory zip code. it is really useful for me
    thanks a lot

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *