How to archive directory using PHP

Last updated on August 8th, 2022 at 10:12 am

Click to rate this tutorial!
[Total: 1 Average: 5]

This is a simple script that archive or zip the current directory using php. Just copy paste the code and run on your host or path where you need the archive to be created.

You can even pass the path as an argument using GET or POST method.

Make sure to modify the path of the directory to be archived by updating this line

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./"));

Complete Code

ini_set("max_execution_time", 1000);
$zip = new ZipArchive();
if ($zip->open($file_name, ZIPARCHIVE::CREATE) !== TRUE) {
die ("Could not open archive, MIGRATION FAILED");
//change the path to be archived accordingly, You can even give the path dynamically using GET or POST method.
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./"));
foreach ($iterator as $key=>$value) {
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
echo "<h1><u>Archive Created Successfully.</u></h1>Download It <a href=".$file_name.">CLICK HERE</a><p>";

We are increasing the max_execution_time runtime configuration to 1000 seconds just in case the directory you need to archive is large and we don’t want the script to timeout. The default for this attribute is 30 seconds.

Note: From the PHP documentation regarding max_execution_time, Your web server can have other timeout configurations that may also interrupt PHP execution. Apache has a Timeout directive and IIS has a CGI timeout function. Both default to 300 seconds. See your web server documentation for specific details.

Click to rate this tutorial!
[Total: 1 Average: 5]

Leave a Reply

Your email address will not be published.