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:
[cc lang='php-brief' ]
$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");
[/cc]
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!