ConfigureWEB Posted November 22, 2012 Share Posted November 22, 2012 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 https://forums.phpfreaks.com/topic/271025-create-and-download-a-zip-archive-from-a-folder/ Share on other sites More sharing options...
DavidAM Posted November 25, 2012 Share Posted November 25, 2012 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 https://forums.phpfreaks.com/topic/271025-create-and-download-a-zip-archive-from-a-folder/#findComment-1394898 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.