Easy Way To Create ZIP File Using PHP

  • Author: Sajjad Hossain
  • |
  • Added: Aug 02, 2016
  • |
  • In: PHP Snippets

In this article I am going to discuss How To Create ZIP File Using PHP. You can create zip folder using PHP and zip file using PHP. You can create zip file easily from your server. if you want to download several files from website backup any data or want to Automatic Backup Website In PHP then you need to know this. Let's see the snippet,


PHP Snippet For ZIP File


we are going to create a function for create zip file in PHP and Zip() is or function. Put some codes into this function,

function Zip($source, $destination)
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}

$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}

$source = str_replace('\\', '/', realpath($source));

if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

foreach ($files as $file)
{
$file = str_replace('\\', '/', realpath($file));

if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}

return $zip->close();
}

How To Use This Snippet


After creating this function now we are able to create any folder or file as ZIP format. Now we need to know how to use this function. Think, You have a directory on your web server and it's name is images and you want to backup this directory. So you need to make it zip first. For creating zip use this function like this,

<?php
$dirname = 'images/';
$newname = 'images.zip';
Zip($dirname,$newname);
?>
If you run this script Zip() function will make your images directory as a ZIP file. Isn't it simple and easy? you can also Unzip a ZIP file from your server easily. You also should know an easy way to extract zip file using PHP. I hope you understand and pick this method easily. If you have any question or comment about this Create ZIP File Using PHP article please don't hesitate to do that, please comment your question in comment section.


Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

NEED HOSTING?
Are you searching for Good Quality hosting?
You can Try It!
Connect Social With PHPAns
Top