ZIP all files in directory and download generated .zip
this will ensure a file with .php extension will not be added:
foreach ($files as $file) {
if(!strstr($file,'.php')) $zip->addFile($file);
}
edit: here's the full code rewritten:
<?php
$zipname = 'adcs.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !strstr($entry,'.php')) {
$zip->addFile($entry);
}
}
closedir($handle);
}
$zip->close();
header('Content-Type: application/zip');
header("Content-Disposition: attachment; filename='adcs.zip'");
header('Content-Length: ' . filesize($zipname));
header("Location: adcs.zip");
?>
ZIP all files and then download
Try this
public string MergeFiles(string folder)
{
using (ZipFile zip = new ZipFile(folder))
{
string[] fileEntries = Directory.GetFiles(folder);
foreach (string f in fileEntries)
{
string path = Path.GetDirectoryName(f.Substring(folder.Length));
zip.AddFile(f, path);
}
zip.Save(folder + "\\files.zip");
}
return folder+"\\files.zip";
}
How to zip a whole folder using PHP
Code updated 2015/04/22.
Zip a whole folder:
// Get real path for our folder
$rootPath = realpath('folder-to-zip');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
Zip a whole folder + delete all files except "important.txt":
// Get real path for our folder
$rootPath = realpath('folder-to-zip');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Initialize empty "delete list"
$filesToDelete = array();
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
// Add current file to "delete list"
// delete it later cause ZipArchive create archive only after calling close function and ZipArchive lock files until archive created)
if ($file->getFilename() != 'important.txt')
{
$filesToDelete[] = $filePath;
}
}
}
// Zip archive will be created only after closing object
$zip->close();
// Delete all files from "delete list"
foreach ($filesToDelete as $file)
{
unlink($file);
}
How to create a zip archive of a directory?
As others have pointed out, you should use zipfile. The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I think it's easiest to explain with some example code:
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, '..')))
with zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
zipdir('tmp/', zipf)
Dowloading a .zip directory with HttpHandler
You could just use WebClient for a 2-liner:
using(Webclient wc = new WebClient())
{
wc.DownloadFile(url, @"D:\downloads\1.zip");
}
Need to ZIP an entire directory using Node.js
I ended up using archiver lib. Works great.
Example
var file_system = require('fs');
var archiver = require('archiver');
var output = file_system.createWriteStream('target.zip');
var archive = archiver('zip');
output.on('close', function () {
console.log(archive.pointer() + ' total bytes');
console.log('archiver has been finalized and the output file descriptor has closed.');
});
archive.on('error', function(err){
throw err;
});
archive.pipe(output);
// append files from a sub-directory, putting its contents at the root of archive
archive.directory(source_dir, false);
// append files from a sub-directory and naming it `new-subdir` within the archive
archive.directory('subdir/', 'new-subdir');
archive.finalize();
Create zip file from all files in folder
Referencing System.IO.Compression and System.IO.Compression.FileSystem in your Project
using System.IO.Compression;
string startPath = @"c:\example\start";//folder to add
string zipPath = @"c:\example\result.zip";//URL for your ZIP file
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
string extractPath = @"c:\example\extract";//path to extract
ZipFile.ExtractToDirectory(zipPath, extractPath);
To use files only, use:
//Creates a new, blank zip file to work with - the file will be
//finalized when the using statement completes
using (ZipArchive newFile = ZipFile.Open(zipName, ZipArchiveMode.Create))
{
foreach (string file in Directory.GetFiles(myPath))
{
newFile.CreateEntryFromFile(file, System.IO.Path.GetFileName(file));
}
}
Create a zip file and download it
Add Content-length
header describing size of zip file in bytes.
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Content-length: " . filesize($archive_file_name));
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
Also make sure that there is absolutely no white space before <?
and after ?>
. I see a space here:
↓
<?php
$file_names = array('iMUST Operating Manual V1.3a.pdf','iMUST Product Information Sheet.pdf');
Related Topics
Strange Behavior When Overriding Private Methods
How to Log into Joomla Through an External Script
Why Are Escape Characters Being Added to the Value of the Hidden Input
Phpmailer Sending Mail to Spam in Hotmail. How to Fix
In PHP, How to Add an Object Element to an Array
How to Minify Js in PHP Easily...Or Something Else
Decoding Numeric HTML Entities via PHP
Sending Sms with Amazon Aws Services PHP
Symfony How to Return All Logged in Active Users
Phpexcel Reader -- Help Required
How to Keep the Chinese or Other Foreign Language as They Are Instead of Converting Them into Codes
Php_Network_Getaddresses: Getaddrinfo Failed: Name or Service Not Known
Accessing Array Values Using Array Key from Twig
Htaccess Access to File by Ip Range
How to Force Formrequest Return JSON in Laravel 5.1