Jump to content

Create And Download A .zip Archive From A Folder


ConfigureWEB

Recommended Posts

Hi,

 

I am trying to create and download a .zip archive from a folder that contains files and folders in it. I have the following code which works for folders that has only files in it but it doesn't work for folders that contain subfolders.

 

<?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);
?>

 

When I run the above code, a .zip archive is created and downloaded but it doesn't open. How should I change it so that it will work for folders that contain files and subfolders?

 

Thanks.

Have a look at the manual page: ziparchive.addemptydir. There are a couple of user comments there with code on how to do that.

 

Basically, in your current code, when "$file" is a directory (is_dir), you have to add an empty directory to the archive, then scan that directory (on the file system) and add all of its files (and directories).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.