How to zip a whole folder using PHP
- Article
- Comment
How to zip a whole folder using PHP . Here we are going to zip the files using php Ziparchive class . Lets get into the topic.
While started creating zip, we need to increase the maximum execution time to 5 mintues or something which is convenient to you.
<?php ini_set("max_execution_time", 300); ?>
This will set to 5 minutes and 300 seconds. and now create an empty Zip archive by using the ziparchive class.
<?php $kv_test_zip_file = new ZipArchive(); ?>
Now, check whether the zip file is created or not with the help of following code.
if ($zip->open("kv_test_zip_file.zip", ZIPARCHIVE::CREATE) !== TRUE) { die ("Sorry the zip files doesnot exist"); }
Now, we need to set the path for the files to add in our zip file
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("pat-to-the-folder/"));
This will get all the listed files path info. And use the following loop to get all the files in the folder.
foreach ($kv_folder as $key=>$value) { $zip->addFile(realpath($key), $key) or die ("ERROR: Problem with file reading : $key"); }
And finally close the zip file.
$zip->close(); echo "Your Zip created successfully.";
That’s it to create a zip file. Test it yourself, if you have any problem with the code comment below.