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,

$dirname = 'images/';
$newname = 'images.zip';
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.

Did you like this article? it will be appreciated if you share a coffee or burger with the author

Sent $5 to the author
Sent $10 to the author

Need Assistance?

I'm Sajjad Hossain, working on web application development since 2012. Do you need assistance on your project? or are you stuck with problems? I am available to help you.
If you want to contact with me ping me at -


We use cookies on our website. To find out more about how and why they are used or opt-out, please read our Cookie Policy. By choosing "I Accept", you consent to our use of cookies. Cookie Policy