Below is the code to generate the zip of multiple files:
<?php
$file1 = 'D:/xampp/htdocs/pdf/pdffiles/14816393105-annexc-form.pdf';
$file2 = 'D:/xampp/htdocs/pdf/pdffiles/14816393105-resident-form.pdf'
$files = array($file1,$file2);
$zipname = time().'-file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
?>
This code does create the zip file but it is corrupted.
EDIT:
zip file is created but if i extract it then it is from the D:/ drive. Means zip file contains this:xampp\htdocs\pdf\pdffiles\file1.pdf
You may specify a filename in addFile method. It is not obvious, since there are no noticeable examples around, but you can use $localname (second parameter) to define and control file/directory structure inside the zip. Use it if you do not want files to be included with their absolute directory tree.
Here is a working example using basename:
$file1 = 'D:/xampp/htdocs/pdf/pdffiles/14816393105-annexc-form.pdf';
// ...
$zip->addFile($file1, basename($file1));
basename returns trailing name component of path, so it will just keep 14816393105-annexc-form.pdf and add it to your zip.
Related
1 - I have a folder has a lot of users folder inside it, and every user's folder has others folders inside it has ismages inside them like this:
localhost/cm/app/model/uploads/mark/3/small/car.jpg
localhost/cm/app/model/uploads/mark/3/big/car.jpg
localhost/cm/app/model/uploads/stiven/9/small/pc.jpg
localhost/cm/app/model/uploads/stiven/9/big/pc.jpg
2 - I want that i donwload this folders with all its content.
3 - I prefer that I download it without zipping it with the same name, if it's not possible with zipping it with any name.
4 - I've used this code and it's not working because when I try to open the zip folder after downloading it an error message appear and tell me that "the archive is either unknown format or damaged", and this my code:
<?php
$dir = 'http://localhost/cm/app/model/uploads'; //folder path
$archive = time().'download.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);
?>
*So how to download my folder with all its folders and images without zipping it or with zipping if not possible?
I suspect you've got an error in you're code. maybe ext-zip isn't install one way of checking this is by running php -m in a terminal which will display all install and enabled modules.
If you open up the zip file with a text editor it's like there be an error message instead of archived data.
This is The best way that i found:
<?php
// Get real path for our folder
$rootPath = realpath('folder_for_ziping');
// 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();
$archive = "file.zip";
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
?>
The function does not seem to be creating the ZIP file properly. The file prompt to downloads works fine. However when opening it, it just creates copy with .cpgz format.
For reference:
foreach ($attachments as $file) outputs as "/upload/image.jpg"
function downloadAttachment() {
$zipname = 'attachments.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($attachments as $file) {
$fileSrc = $_SERVER['DOCUMENT_ROOT'] . $file["file_attachment"];
$zip->addFile($fileSrc);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
ob_clean();
flush();
readfile($zipname);
}
You can use dirname(__FILE__) - it return you absolute path to your current php script, make var_dump( dirname(__FILE__) ) to see what it gives you and then relocate with ../ or /folders/.. to your attachments directory
so your $zipname will be something like $zipname = dirname(__FILE__) .'/../some_folders/attachements/attachments.zip';
and make sure that directory is writable by www-data user or just chmod it 0777 in any case
__FILE__ is one of PHP's magic constants you can check more here - http://php.net/manual/en/language.constants.predefined.php
one more good practice is to define somewhere in configs.php which is included on every php define('ROOT_DIR', "absolute root path of your project"); then use ROOT_DIR variable everywhere in your project as prefix for all folders ROOT_DIR."/folder/file ..."
I am trying to add functionality to my website where users can download multiple image files via a single .zip folder. Currently I have this code executing but when i open the downloaded zip file it extracts another zip file my-archive (3) 2.zip.cpgz and every time I try to open it, it extracts yet another zip file.
Here is my basic code using php native zip feature.
$image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg";
$image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";
$files = array($image1, $image2);
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
EDIT
I am trying hard to get the provided answer to work. I just tried the most recent edit and got this error
]
You should download external files and then archive them.
$image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg";
$image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";
$files = array($image1, $image2);
$tmpFile = tempnam('/tmp', '');
$zip = new ZipArchive;
$zip->open($tmpFile, ZipArchive::CREATE);
foreach ($files as $file) {
// download file
$fileContent = file_get_contents($file);
$zip->addFromString(basename($file), $fileContent);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=file.zip');
header('Content-Length: ' . filesize($tmpFile));
readfile($tmpFile);
unlink($tmpFile);
In example above I used file_get_contents function, so please enable allow_url_fopen or use curl to download the files.
Hi guys above code worked perfectly. Images download worked only on live server (only if we use https or http). But it is not worked in local (if we use https or http)..
If you use local follow this -> Only change below lines.
For local use below img's
$image1 = "C:/Users/User/Pictures/Saved Pictures/chandamama.jpg";
$image2 = "C:/Users/User/Pictures/Saved Pictures/beautifull.jpg";
Do not use below img's for local.
$image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg";
$image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";
I know there is many questions regarding the ZipArchive and how it works but after following all these I still can't get my program to work.
I don't know where i'm going wrong because I have die methods in and none of them are getting activated.
$path = "/export/scripts/CLOUD/logs/web/Private_Testbox/Jan_28_2013_16_20_44_atvts78_rollout_config/";
$fileName = explode('/', $path);
$zipname = $fileName[count($fileName) - 2];
$zip = new ZipArchive;
$handle = opendir($path);
//Check whether Zip can be opened
if ($zip->open($zipname, ZIPARCHIVE::CREATE) !== TRUE) {
die("Could not open archive");
}
//Add all files to an array
while ($file = readdir($handle))
{
$zip->addFile($path, $file);
}
closedir($handle);
$zip->close();
//Send zip folder
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=' . $zipname . '.zip');
readfile($zip);
This file downloads the zip folder but there is never anything in it.
Thanks for help in advance.
You forgot a die() on the ->addFile() call, which means you're assuming that the files actually got added.
readfile() does not return the full path to a file in a directory, only the actual "local" filename, which means you're adding files which don't exist in the script's current working directory. Try:
$zip->addFile($file, $path . $file);
^^^^^^^^^^^^^^^^^^^^^
instead. As it stands now, your code is using $path as the filename to embed in the zip, and directories cannot be used as filenames. And without the $path . $file, addFile is looking in the wrong spot, e.g. it's the equivalent of getcwd() . $file instead.
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();