create create zip File and Extract zip File in php

In this artical we will show you how to create create zip File and Extract zip File in php.

PHP has give class ZipArchive to create and manipulate for Zip files.

open()open() use of open/create any zip file using ZipArchive class
addFile()addFile() use of adding the files to archieve using ZipArchive class
close()close() use of safely close the zip file using ZipArchive class
extractTo()extractTo() use of extracting the zip file using ZipArchive class

How to create .zip File using PHP

// ZipArchive for Creating object
$zip_val = new ZipArchive();

$temp_set = 1;
$set_files= "sample_master.zip";

if($zip_val->open($set_files,$temp_set?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)===TRUE)
{
// Add css files to the .zip file()
$zip_val->addFile("sample_master.css");

// This means sample_style.css will be added as sample_new_style.css
$zip_val->addFile("sample_style.css", "sample_new_style.css");

$zip_val->addFile("sample_fonts.css");

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

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

Extract .zip file using PHP

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

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

// Extract only several files

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

// Open sample_master.zip for extracting multiple files
if ($zip->open("sample_master.zip") === TRUE)
{
// Will extract only sample_fonts.css and sample_master.css
// from sample_master.zip to given path.
$set_files = array("sample_fonts.css","sample_master.css");
$zip_val->extractTo("/path/to/folder/",$set_files);
$zip_val->close(); // close
}

Leave a Comment

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

  +  33  =  34

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US