How can I download multiple files as a zip-file using php?
You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:
$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
and to stream it:
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.
This is a working example of making ZIPs in PHP:
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
echo $path = "uploadpdf/".$file;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));
}
else{
echo"file does not exist";
}
}
$zip->close();
Create a zip file, then download the file, by setting the header, read the zip contents and output the file.
http://www.php.net/manual/en/function.ziparchive-addfile.php
http://php.net/manual/en/function.header.php
You are ready to do with php zip lib,
and can use zend zip lib too,
<?PHP
// create object
$zip = new ZipArchive();
// open archive
if ($zip->open('app-0.09.zip') !== TRUE) {
die ("Could not open archive");
}
// get number of files in archive
$numFiles = $zip->numFiles;
// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
$file = $zip->statIndex($x);
printf("%s (%d bytes)", $file['name'], $file['size']);
print "
";
}
// close archive
$zip->close();
?>
http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/
and there is also php pear lib for this
http://www.php.net/manual/en/class.ziparchive.php
Related
How can I download multiple files as a zip-file using php?
You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:
$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
and to stream it:
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.
This is a working example of making ZIPs in PHP:
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
echo $path = "uploadpdf/".$file;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));
}
else{
echo"file does not exist";
}
}
$zip->close();
Create a zip file, then download the file, by setting the header, read the zip contents and output the file.
http://www.php.net/manual/en/function.ziparchive-addfile.php
http://php.net/manual/en/function.header.php
You are ready to do with php zip lib,
and can use zend zip lib too,
<?PHP
// create object
$zip = new ZipArchive();
// open archive
if ($zip->open('app-0.09.zip') !== TRUE) {
die ("Could not open archive");
}
// get number of files in archive
$numFiles = $zip->numFiles;
// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
$file = $zip->statIndex($x);
printf("%s (%d bytes)", $file['name'], $file['size']);
print "
";
}
// close archive
$zip->close();
?>
http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/
and there is also php pear lib for this
http://www.php.net/manual/en/class.ziparchive.php
To put it simply, I would like my users to be able to download their website files, so I created a "Download Website" button which uses this script to add all files/folders in their directory which is in the variable $direc and archive those files/folders.
<?
///////// DOWNLOAD ENTIRE WEBSITE:
if(isset($_POST['download_site'])){
// define some basics
$rootPath = '../useraccounts/'.$direc.'';
$archiveName = ''.$direc.'.zip';
// initialize the ZIP archive
$zip = new ZipArchive;
$zip->open($archiveName, ZipArchive::CREATE);
// create recursive directory iterator
$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
// let's iterate
foreach ($files as $name => $file) {
$filePath = $file->getRealPath();
$zip->addFile($filePath);
}
// close the zip file
if (!$zip->close()) {
echo '<p>There was a problem writing the ZIP archive.</p>';
} else {
echo '<p>Successfully created the ZIP Archive!</p>';
}
}
?>
To my surprise, this code works. Although, there are a few hiccups:
It doesn't automatically force a download of that archive.
It adds the archive in to my main directory rather than moving it to a separate directory of my choice such as site_downloads or deletes it up on completed download.
Are these problems at all fixable or if not, is there a better way to do it so my main directory does not get filled with constant downloads? I guess it will cause a problem once a Archive is created more than once, as it uses the Directory name.
Solved this by using a few different combinations:
<?
///////// DOWNLOAD ENTIRE WEBSITE:
if(isset($_POST['download_site'])){
// define some basics
$rootPath = '../useraccounts/'.$direc.'';
$archiveName = ''.$direc.'.zip';
// initialize the ZIP archive
$zip = new ZipArchive;
$zip->open($archiveName, ZipArchive::CREATE);
// create recursive directory iterator
$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
// let's iterate
foreach ($files as $name => $file) {
$filePath = $file->getRealPath();
$zip->addFile($filePath);
}
// close the zip file
if (!$zip->close()) {
echo '<p>There was a problem writing the ZIP archive.</p>';
} else {
rename($archiveName, 'user_archives/'.$archiveName.'');
$yourfile = "user_archives/".$archiveName."";
$file_name = basename($yourfile);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($yourfile));
readfile($yourfile);
ignore_user_abort(true);
if (connection_aborted()) {
unlink('user_archives/'.$archiveName.'');
} else {
unlink('user_archives/'.$archiveName.'');
}
echo '<p>Successfully created the ZIP Archive!</p>';
}
}
?>
This seems to fix all problems.
currently I am trying to put files in a zip and download them. I use the following code:
# create new zip opbject
$zip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
# loop through each file
foreach($files as $file){
# download file
$download_file = file_get_contents($file);
#add it to the zip
$zip->addFromString(basename($file),$download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename=Resumes.zip');
header('Content-type: application/zip');
readfile($tmp_file);
The files are added to the array the following way:
$weborder = $_POST['weborder'];
$printlocation = $_POST['print'];
$dir = "z:\Backup\\$printlocation\\$weborder.zip";
$zip = new ZipArchive;
$files = array();
if ($zip->open($dir))
{
for($i = 0; $i < $zip->numFiles; $i++)
{
if ($zip->getNameIndex($i) != "order-info.txt" && $zip->getNameIndex($i) != "workrequest.xml" && $zip->getNameIndex($i) != "workrequest.pdf")
{
$filename = $zip->getNameIndex($i);
$files[$i] = $dir . "\\" . $filename;
}
}
}
This downloads the zip and the files that are in the zip. The only problem I am having is that the files are empty.
instead of
$zip->addFromString(basename($file),$download_file);
try
$zip->addFile($basename($file));
This code is working make sure that your files are existed or not.
$array = array("sites/README.txt","sites/chessboard.jpg"); //files to Add/Create in zip file
$zip = new ZipArchive(); // Load zip library
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
{
// Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($array as $key => $value)
{
if(file_exists($value)){
$zip->addFile($value); // Adding files into zip
}else{echo $value ." file not exist<br/>";}
}
$zip->close();
if(file_exists($zip_name))
{
echo "yes";die;
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}else{echo "zip not created";die; }
For Download Existing file
$zip_name = "YOUR_ZIP_FILE PATH";
if(file_exists($zip_name))
{
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
//unlink($zip_name);
}else{
echo "zip not created";exit;
}
I have lots of files in a particular Directory. In a certain PHP page I lists the contents of the particular directory with links to download each item separately. Now I need to display a Link which will ZIP all the contents of that directory so any visitor can download all the contents as a Single ZIP file.
Use ZipArchive for zipping files and RecursiveDirectoryIterator for getting all files in a directory
something like
$zipfilename = <zip filename>;
$zip = new ZipArchive();
$zip->open($zipfilename, ZipArchive::CREATE);
// add all files in directory to zip
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('path/to/files/')) as $filename) {
$zip->addFile($filename);
}
$zip->close();
Then send the zip to the browser
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename="'. $zipfilename .'"');
header('Content-Length: ' . filesize($zipfilename));
readfile($zipfilename);
Obviously you could post the directory name and event the zip file name to the script but it gives you a starting point
Try this
$files = array('file1.txt', 'file2.txt', 'file3.txt');
$zip = new ZipArchive;
$zip->open('file.zip', ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
This question already has answers here:
Dynamically creating zip with php
(2 answers)
Closed 9 years ago.
Hi frnds can anyone tel me how to Create a Zip File Using PHP?
Actually i am having 10 files with boxes,if i select more than one check box that files should get zip/rar and i am able to save that in some path..
Please can anyone help in this solution as i am new to php
$zip_name = 'path/to/final.zip'; //the real path of your final zip file on your system
$zip = new ZipArchive;
$zip->open($zip_name, ZIPARCHIVE::CREATE);
foreach($files as $file)
{
$zip->addFile($file);
}
$zip->close();
header('Content-type: application/zip');
header('Content-disposition: filename="' . $zip_name . '"');
header("Content-length: " . filesize($zip_name));
readfile($zip_name);
exit();
// This example creates a ZIP file archive test.zip and add the file /path/to/index.txt. as newname.txt.
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFile('/path/to/index.txt', 'newname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
//include your connection file
//$file_names[] get your files array
//$error = ""; //error holder
//$file_path='set your image path' folder to load files
if(extension_loaded('zip'))
{ // Checking ZIP extension is available
if(count($file_names) > 0)
{
// Checking files are selected
$zip = new ZipArchive(); // Load zip library
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){ // Opening zip file to load files
$error .= "* Sorry ZIP creation failed at this time<br/>";
}
foreach($file_names as $file){
$zip->addFile($file_path.$file); // Adding files into zip
}
$zip->close();
if(file_exists($zip_name))
{
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}
}
else
{
$error .= "* Please select file to zip <br/>";
}
}
else
{
$error .= "* You dont have ZIP extension<br/>";
}
?>