laravel return download creates extra file - php

I'm using following codes to create zip file in Laravel:
$files = Answer::where('questionid', $questionId)
->pluck('answer')
->all();
$zip = new ZipArchive;
$zip_name = time() . "_$questionId" . ".zip";
if ($zip->open(storage_path($zip_name), ZipArchive::CREATE) === true) {
foreach ($files as $file) {
$relativeNameInZipFile = explode('/', $file)[3];
$zip->addFile(Storage::path($file), $relativeNameInZipFile);
}
$zip->close();
}
return Storage::download($zip_name);
It works properly.But when the last line of the code that returns file to download create an extra zip file in the storage!
return Storage::download($zip_name);
Why!!??

Related

File does not exist while downloading Zip file in Laravel

I'm getting error as the "file does not exist" as folder does exist.
The file "../storage/app/public/bks/case_1/XsIbdGSJow7O3fhq9LyU.zip" does not exist
I have checked with Database field name zipname is not present but job_id is present. I'm not sure but do we have to have field name as zipname present in Database for this to download.
public function downloadZip(Request $request)
{
#$job_id = $request->job_id;
#$filenames = DB::table('analytics_report')->where('job_id',$job_id)->get()->pluck('filename')->toArray();
#$zipname = $request->job_id;
$zip = new \ZipArchive;
$zip->open($zipname, \ZipArchive::CREATE);
foreach ($filenames as $filename){
$zip->addFile($filename);
}
$zip->close;
#$path = '../storage/app/public/bks/case_1/'.$zipname;
return response()->download($path);
}
Thanks!
You have a typo here $zip->close;. Should be $zip->close();
Your code needs some checks before everything else.
public function downloadZip(Request $request)
{
if($request->has("job_id") === false) return;
$job_id = $request->job_id;
$filenames = DB::table('analytics_report')
->where('job_id',$job_id)
->get()
->pluck('filename')
->toArray();
if (count($filenames) == 0) return;
$zipname = $request->job_id;
$zip = new \ZipArchive;
$zip->open($zipname, \ZipArchive::CREATE);
foreach ($filenames as $filename){
$zip->addFile($filename);
}
$zip->close();
$path = stprage_path('app/public/storage/bks/case_1/'.$zipname);
return response()->download($path);
}

why does the zip folder is not created with PHP

I'm trying to make a existing folder to a zip and download it using php. The existing folder contain some files. This is my code
$folder = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.']';
$zip_name = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.'].zip';
$zip = new ZipArchive;
if($zip -> open($zip_name, ZipArchive::CREATE ) === TRUE) {
$dir = opendir($folder);
while($file = readdir($dir)) {
if(is_file($folder.$file)) {
$zip -> addFile($folder.$file, $file);
}
}
$zip ->close();
}
But when i called the API zip folder is not created. Please go through my code and help me to solve it. Thanks in advance
// 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();
Try below code.
$folder = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.']';
$zip_name = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.'].zip';
$zip = new ZipArchive;
$zip->open($zip_name, ZipArchive::CREATE);
foreach (glob($folder) as $file) {
$zip->addFile($file);
}
$zip->close();

how to create a zip file from a folder - php

I have a problem.
I searched the internet for a solution, but nothing works well. I'm trying to make a script that will take files from a folder and threw them into a zip archive.
But it doesn't work ..
I tried through different paths, but it's only me mixed up and nothing came of it.
Here is the current code that is according to me the easiest and should workbut doesn't do that ..
Can you help me?
function archivebackup(){
$zip = new ZipArchive;
if ($zip->open('Mail.zip', ZipArchive::CREATE) === TRUE){
foreach (new DirectoryIterator('Mails/') as $fileInfo) {
$fileName = $fileInfo->getFilename();
// echo $fileName ."<br>";
$zip->addFile($fileName);
}
$zip->close();
}
}
It seems you're not including files in your current working directory and getFilename() only returns a filename without a path.
Do the following:
function archivebackup(){
$zip = new ZipArchive;
if ($zip->open('Mail.zip', ZipArchive::CREATE) === TRUE){
foreach (new DirectoryIterator('Mails/') as $fileInfo) {
if (in_array($fileInfo->getFilename(), [ ".", ".." ]) { continue; }
$fileName = $fileInfo->getPathname();
$zip->addFile($fileName);
}
$zip->close();
}
}

fails with ZipArchive

i will create a Zip Archive with the PHP Class. But it still not working.
It comes no fail and the response is 1. He don't create the Zip-File.
$zip = new ZipArchive;
$res = $zip->open('qr_img/'.'ab387bas.zip'.'', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFile($file, 'screen.png');
$zip->close();
}
know's everyone the answer ?
$file_names is the array of files which are you want to add in the zip.
function zipFile($file_names,$archive_file_name)
{
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::OVERWRITE )!==TRUE) {
}
//add each files of $file_name array to archive
foreach($file_names as $files)
{
// $zip->addFile($files,$files);
$zip->addFromString(basename($files), file_get_contents($files));
}
$zip->close();
}

php creating zips without path to files inside the zip

I'm trying to use php to create a zip file (which it does - taken from this page - http://davidwalsh.name/create-zip-php), however inside the zip file are all of the folder names to the file itself.
Is it possible to just have the file inside the zip minus all the folders?
Here's my code:
function create_zip($files = array(), $destination = '', $overwrite = true) {
if(file_exists($destination) && !$overwrite) { return false; };
$valid_files = array();
if(is_array($files)) {
foreach($files as $file) {
if(file_exists($file)) {
$valid_files[] = $file;
};
};
};
if(count($valid_files)) {
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
};
foreach($valid_files as $file) {
$zip->addFile($file,$file);
};
$zip->close();
return file_exists($destination);
} else {
return false;
};
};
$files_to_zip = array('/media/138/file_01.jpg','/media/138/file_01.jpg','/media/138/file_01.jpg');
$result = create_zip($files_to_zip,'/...full_site_path.../downloads/138/138_files.zip');
The problem here is that $zip->addFile is being passed the same two parameters.
According to the documentation:
bool ZipArchive::addFile ( string $filename [, string $localname ] )
filename
The path to the file to add.
localname
local name inside ZIP archive.
This means that the first parameter is the path to the actual file in the filesystem and the second is the path & filename that the file will have in the archive.
When you supply the second parameter, you'll want to strip the path from it when adding it to the zip archive. For example, on Unix-based systems this would look like:
$new_filename = substr($file,strrpos($file,'/') + 1);
$zip->addFile($file,$new_filename);
I think a better option would be:
$zip->addFile($file,basename($file));
Which simply extracts the filename from the path.
This is just another method that I found that worked for me
$zipname = 'file.zip';
$zip = new ZipArchive();
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
$download_file = file_get_contents($file);
$zip->addFromString(basename($file),$download_file);
$zip->close();
header('Content-disposition: attachment; filename='.$zipname);
header('Content-type: application/zip');
readfile($tmp_file);
I use this to remove root folder from zip
D:\xampp\htdocs\myapp\assets\index.php
wil be in zip:
assets\index.php
our code:
echo $main_path = str_replace("\\", "/", __DIR__ );// get current folder, which call scipt
$zip_file = 'myapp.zip';
if (file_exists($main_path) && is_dir($main_path))
{
$zip = new ZipArchive();
if (file_exists($zip_file)) {
unlink($zip_file); // truncate ZIP
}
if ($zip->open($zip_file, ZIPARCHIVE::CREATE)!==TRUE) {
die("cannot open <$zip_file>\n");
}
$files = 0;
$paths = array($main_path);
while (list(, $path) = each($paths))
{
foreach (glob($path.'/*') as $p)
{
if (is_dir($p)) {
$paths[] = $p;
} else {
// special here: we remove root folder ("D:\xampp\htdocs\myapp\") :D
$new_filename = str_replace($main_path."/" , "", $p);
$zip->addFile($p, $new_filename);
$files++;
echo $p."<br>\n";
}
}
}
echo 'Total files: '.$files;
$zip->close();
}

Categories