32,000+ SUBSCRIBERS CAN'T GO WRONG !!!

phpans
GET TOP ARTICLES, SNIPPETS, SCRIPTS IN YOUR INBOX FOR FREE!

Delivered by GET EMAIL UPDATES FeedBurner
We always respect your privacy and take protecting it seriously.
We won't Spam You

Easy Way To Create ZIP File Using PHP

, 0,
Easy Way To Create ZIP File Using PHP
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.

Download PDF
Is this article helpful for you?





captcha

  • Connect
  •       
Top
Create an free account and start learning & sharing! Sign Up