Dynamically Creating zip files using php

Creating .ZIP archives using PHP can be just as simple as creating them on your desktop. PHP’s ZIP class provides all the functionality you need! The script below will make a zip file based on a users profile name, add up to 3 files if the exist download it and delete the temporary file.

The script (or at least the location of the temporary file needs to be located in a writeable directory).

$zip = new ZipArchive();
$filename = $profilename.".zip";

if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}

if($biog){
$zip->addFile("../$biog", "Biography.doc");
}

if($additionalinfodownload){
$zip->addFile("../$additionalinfodownload", "Additional-Information.doc");
}

if($publications){
$zip->addFile("../$publications", "Publications.doc");
}

$zip->close();

header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$filename");

unlink("$filename");

Tags: ,

About Keiron

Web Developer based in the UK. Click here if you want to work with me