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.

Link to comment
Share on other sites

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).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.