Downloading multiple files using PHP ZipArchive - php

I am trying to randomly download some files.
I apologize because I posted it earlier but can someone explain what I am doing wrong in detail?
I can not seem to debug it as I know minimal php.
<?php
$rootPath = realpath('./uploads');
//make zip file
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$nfiles = glob($rootPath.'*.{aiff}', GLOB_BRACE);
$files = array_rand($nfiles, 20);
foreach($files as $file) {
$pathtofile = $nfiles[$file];
if (!$file->isDir())
{
// Get path for current file
$filePath = $pathtofile->getRealPath();
$relativePath = str_replace($rootPath, "", $file);
// Add file to zip
$zip->addFile($filePath, $relativePath);
}
}
//-------------------------------------------//
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment;
filename='.'generatedsounds.zip');
header('Content-Length: ' . filesize('file.zip'));
readfile('file.zip');
if(file_exists('file.zip'))
{
unlink('file.zip');
}
?>

You're calling ->isDir() method which is not defined, And you're calling ->getRealPath() which is also not defined.
And you're getting all files then selecting 20 random files from the array (why??)
While you are rewriting the headers, errors won't be shown in browser, try without rewriting headers which means it's kept as html header and test until you get a binary file output then add the headers back so you have a working code.

Related

How to download a folder with all its folders and files without zipping it with php

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);
?>

not able to create zip file in codeigniter

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\pd‌​f\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.

Compress the files while downloading by client

I try to develop something like dropbox(very basic one). For one file to download, it's really easy. what i want is: when client asks me big file, i zip file in server side then send to user. But if file is too big it takes too many times to zip them and send to user.
is there any way to send files while they are compressing?
thanks for your help. Here is my simple sample code
<?php
function createzip($files, $zip_file) {
$zip = new ZipArchive;
if($zip->open($zip_file, ZipArchive::CREATE) === TRUE) {
foreach($files as $file){
$zip->addFile($file);
}
$zip->close();
return true;
}
else return false;
}
$ss=array("jj.mp4");
createzip($ss,'archiv.zip');
if(filesize("archiv.zip")>3000){
$vv=array("archiv.zip");
createzip($vv,"bbb.zip");
}
?>
use do while loop in if statement. Until file size become a desired value. I don't understand how to use do while loop and does it make it that type of compresses. Please help me out.
I use a method like this but I get file names from database if you wanna check and adapt to your codes..
$FList = $dl->select('dosyaYolu0, dosyaYolu1, dosyaYolu2, dosyaYolu3, dosyaYolu4')->table('tb_gelenEvrak')->where('mesajKodu', $filesnorm)->get();
$files = array(''.$FList->dosyaYolu0.'', ''.$FList->dosyaYolu1.'', ''.$FList->dosyaYolu2.'',''.$FList->dosyaYolu3.'', ''.$FList->dosyaYolu4.'');
$zipname = $filesnorm.'.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);

PHP ZipArchive download working but not adding files to zip

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.

How to make the contents in a directory to be downloaded as a ZIP file using PHP?

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();

Categories