Page 1 of 1

PHP Tutorial: Creating .zip Files

Posted: Thu Nov 22, 2012 9:34 am
by nyo
I am trying to create and download a .zip archive from a folder that contains files and folders in it. I watched the tutorial on:

http://www.youtube.com/watch?v=6qCb0rLGT48

It shows how to create a .zip file for a folder that contains files only. I have the following code at the moment:
<?php
$dir = 'sample';

$archive = 'sample.zip';

$zip = new ZipArchive;
$zip->open($archive, ZipArchive::CREATE);

$files = scandir($dir);
unset($files[0], $files[1]);
foreach ($files as $file) {
	$zip->addFile($dir.'/'.$file);
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
?>
It works for folders that has only files in it but it doesn't work for folders that contain subfolders. The .zip archive is created and downloaded but it doesn't open. How should I change it so that it will work for folders with subfolders too?

Thanks.

Re: PHP Tutorial: Creating .zip Files

Posted: Sun Nov 25, 2012 1:34 am
by jacek
The reason it doesn't open is probably because the page is generating an error which makes the file invalid. Try commenting out everything after $zip->close() and run it again, that might show up the problem.