7-29-2010 Dynamically Creating Zip Archives with PHP

Never having had the need to create a zip archive manually via PHP before, I was a little worried that it’d be a pain.  Not so!  In fact, it was extremely simple.  I first googled up this tutorial which set up the basics for me and working from there and with the PHP docs online, I was able to complete the project in almost no time at all.

One thing that was a little complicated was cleaning up after I finished.  I didn’t want to remove the zipped files and the archive before I could feel confident that the visitor to the site had downloaded everything they wanted to.  Thus, a separate process had to do the clean-up operation.  I opted to add some code to the index.php file within the same folder as all the created, temporary files.  Then, when someone visited it, that code would clean-up all the extraneous files.

Here’s what I did:

1
2
3
4
5
6
7
8
9
10
11
$now = time();
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("."));
foreach($iterator as $file) {
     if(substr($file, -3, 3) == "php" || $file->getFilename() == "template.docx" || ($now - $file->getCTime())  < 300) continue;
     $temp = explode(DIRECTORY_SEPARATOR, $file);
     $folders[] = $temp[1];
     unlink($file);
}

$folders = array_unique($folders);
foreach($folders as $folder) rmdir("./$folder");

The if-conditional just makes sure that I don’t delete php files, the template word document from which others are generated, or any files that are less than 5 minutes old.  That time constraint makes me feel like anyone who doesn’t get the files they wanted probably didn’t click the Open/Save button in the dialog after making the files and they can just re-do the work.

How did I use the template document to make new ones, you ask?  The PHPWord class, that’s how!

  1. Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  2. If you're seeing this field, or being told about it via a screen reader, I apologize for any inconvenience. It's a honeypot to catch some spam bots and must be left blank. In fact, if you put anything in it, your comment will be rejected!