Tuesday, April 17

Working ZipArchive

Ok, I finally got it and feel really dumb now. It turned out to be the bane of my existence.... permissions. What would make me thing the IUSR_SERVERNAME account would only need write permissions. To change a file, of course they would need modify permissions too! DUH!

I figured a lot of other things out along the way too. Like: ZipArchive likes relative, not absolute paths. I had to rewrite some stuff because of that. I had been using 7za.exe, but wanted to start using the php_zip.dll since I upgraded to php5.

So here's my code for pulling file names from a database and stuffing them into a zip. I turned it into a function that throws back the zip file name. These are zips of the files in a bunch of teachers' lesson plans.

function zipper($id){
include 'db.php';
$query = mysql_query("select distinct path from files where id=".$id."");
$query2 = mysql_query("select title from lessons where lesson_id=".$id."");
$row = mysql_fetch_assoc($query2);
$zipfile = str_replace(" ", "", $row['title']).".zip";
$filename = "teacherfiles/zips/$zipfile";
//create archive
$zip = new ZipArchive();
if($zip->open($filename, ZIPARCHIVE::CREATE)!=TRUE){
exit("Cannot open $filename");
}

while($result = mysql_fetch_assoc($query)){
$path = str_replace("%20"," ",str_replace("&","&",$result['path']));
$zip->addFile($path);
}
$zip->close();

return $filename;
}

What happens is I call a popup window, which calls the function, makes the zip, then uses a meta-redirect to the created file to prompt a download. After 30 seconds, the window redirects to a page that deletes the file and closes the window almost immediately. It's pretty cool.

No comments: