PHP Tutorial: Creating .zip Files

Post here is you are having problems with any of the tutorials.
Post Reply
nyo
Posts: 124
Joined: Mon May 09, 2011 1:55 pm
Location: Mobile

PHP Tutorial: Creating .zip Files

Post 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.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: PHP Tutorial: Creating .zip Files

Post 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.
Image
Post Reply