Undefind Property Error while creating Zip file in Laravel using ZipArchive - php

I'm getting following Error while to creating Zip file in laravel using ZipArchive which will have all the PDF files
"Undefined property: ZipArchive::$close"
CONTROLLER:
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;
}

$zip->close();
You're missing the parantheses to make it a function call - currently you're trying to access a property $close on $zip, which doesn't exist.

Related

I am trying to download multiple image as a zip file but getting error using laravel 7

I am trying to download multiple images as a zip file but getting errors
Invalid argument supplied for foreach() please help me how i resolve that thanks.
Check the error: https://flareapp.io/share/47qG2A3m
Controller
public function dowloads($id)
{
$url = config('yourstitchart.file_url');
$zip = new ZipArchive;
$inboxFiles = Inbox::where('id', $id)->first()->file;
// $inboxFiles = "["phpCM0Yia.png","phptLC57a.png"]"
foreach ($inboxFiles as $file) {
$zip->add($url . $file); // update it by your path
}
$zip->close();
return response()
->download(
public_path('/temporary_files/' . "deals.zip"),
"deals.zip",
["Content-Type" => "application/zip"]
);
}
You are returning a string, you can't handle it like an array.
It's JSON, you can just use :
$inboxFiles = json_decode(Inbox::where('id', $id)->first()->file);
(the above code is not really robust, but you have the way)
I know this has already been answered, but do not use json_decode any more in Laravel...
Cast the field file as a JSON/array, so it will automatically be an array and when you save it in the database, it will be transformed to JSON, and when you want to read it back, it will be automatically transformed to array...
To do so, you have to edit Inbox model and add this property:
protected $casts = ['file' => 'array'];
And that's it, then you have to use the field as if it is already an array, so leaving your code as it is in your question, without any edit, it will work right away:
public function dowloads($id)
{
$url = config('yourstitchart.file_url');
$zip = new ZipArchive;
$inboxFiles = Inbox::where('id', $id)->first()->file;
// $inboxFiles = "["phpCM0Yia.png","phptLC57a.png"]"
foreach ($inboxFiles as $file) {
$zip->add($url . $file); // update it by your path
}
$zip->close();
return response()
->download(
public_path('/temporary_files/' . "deals.zip"),
"deals.zip",
["Content-Type" => "application/zip"]
);
}

Download multiple uploaded files in Laravel

I have a form input which can upload multiple files. So all the files paths are saved in the database as an array of strings . Below is my controller to download the files. I wanted to know how I can go about presenting each file to be downloaded in blade view. So I could download a single file at a time. My controller below. It works only when downloading a single file. I get this error Invalid argument supplied for foreach().
public function download($id) {
$deal = Deal::findorFail($id);
$files = $deal->uploads;
foreach ($files as $file) {
return Storage::download($file);
}
}
public function download($id) {
$deal = Deal::findorFail($id);
$files = $deal->uploads;
foreach ($files as $file) {
return Storage::download($file);
--------^^^^^^-------------------------
}
}
when you return first file, it breaks foreach loop. So you have to return all files together. And only way to achieve this, is creating a zip file that contains all files..
For this purpose you may use chumper/zipper package
$zipper = Zipper::make(public_path('/documents/deals.zip'));
foreach ($files as $file) {
$zipper->add(public_path($file)); // update it by your path
}
$zipper->close();
return response()
->download(
public_path('/temporary_files/' . "deals.zip"),
"deals.zip",
["Content-Type" => "application/zip"]
);
update
Add accessor to Deal model to get files as array
Deal Model
php artisan getUploadsAttribute($attribute){
return explode(",",$attributes);
}

Laravel Create and Download Zipped File

I'm having trouble on Creating and downloading Zip file
I see on this code on
http://laravelcode.com/post/how-to-create-zip-file-in-laravel-using-ziparchive
This is my controller
public function download(){
$FOLDERID = $_GET['id'];
$FILEPATH = *My Database Query*
$PATHTOFILE = public_path().'/images/';
$ZIPNAME = 'ZIPFILENAME.zip';
$ZIP = new ZipArchive;
if ($ZIP->open($PATHTOFILE.'/'.$ZIPNAME, ZipArchive::CREATE) === TRUE) {
$FILES = *My Database Query to get file*
foreach ($FILES as $FILE) {
$ZIP->addFile($FILE->File_Path , $FILE->File_Name);
}
$ZIP->close();
}
else{
return "NO FILES CREATED";
}
and I dont know what this one do
$HEADERS = array(
'Content-Type' => 'application/octet-stream',
);
And this one is for download the zip
if(file_exists($PATHTOFILE)){
return Response()->download($PATHTOFILE, $ZIPNAME, $HEADERS);
}else{
return "asd";
}
still didnt know what #HEADERS do
Im having trouble on Creating Zip File, The error always on the $ZIP->close();
It says
ZipArchive::close(): Read error: Bad file descriptor
can you guys help me which one i did wrong?
Thankyou in advance!
create route
Route::get('download-zip', 'ZipController#downloadZip');
step:2 Create Controller
add one new method for route. downloadZip() will generate new zip file and download as response, so let's add below:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
use ZipArchive;
class ZipController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function downloadZip()
{
$zip = new ZipArchive;
$fileName = 'myNewFile.zip';
if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE)
{
$files = File::files(public_path('myFiles'));
foreach ($files as $key => $value) {
$relativeNameInZipFile = basename($value);
$zip->addFile($value, $relativeNameInZipFile);
}
$zip->close();
}
return response()->download(public_path($fileName));
}
}

PHP ZipArchive Not Working in Laravel

PHP ZipArchive is working perfectly if I run it in raw php, but getting a "class not found" error when I try to run it in my Laravel project:
FatalErrorException in WidgetController.php line 40:
Class 'App\Http\Controllers\ZipArchive' not found
Here's the function I have in my laravel controller:
public function installHello()
{
$file_path = base_path("resources/assets/packages/helloworld.zip");
$zip = new ZipArchive;
if ($zip->open($file_path) === TRUE) {
$zip->extractTo(base_path('packages/tkabir/'));
$zip->close();
return redirect()->back();
//echo 'ok';
} else {
echo 'failed';
}
}
And here's the sample I tried in an index.php file:
<?php
$zip = new ZipArchive;
if ($zip->open('E:/xampp/htdocs/ziptest/helloworld.zip') === TRUE) {
$zip->extractTo('E:/xampp/htdocs/ziptest/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
Any idea why it wouldn't work in laravel?
Problem solved. Made an obvious mistake: forgot to ''use ZipArchive'' in my Laravel controller
Add use ZipArchive; in your controller, this work for me.
On composer.json add line:
"require": {
[...]
"ext-zip": "*" /* this line */
},
Execute:
composer update
On your controller use this lines:
use ZipArchive;
[...]
// use this form to instance the object
$zip = new \ZipArchive();

PHP RecursiveIteratorIterator: The system cannot find the path specified?

I have this error when I want to autoload classes with RecursiveIteratorIterator and spl_autoload_register,
uncaught exception 'UnexpectedValueException' with message
'RecursiveDirectoryIterator::__construct(): The system cannot find the
path specified. (code: 3)
What does it mean?
Below is my class autoloader,
function autoload_multiple_directory($class_name){
// List all the class directories in the array.
$array_directories = array(
'core/controller/',
'core/model/',
'core/helper/',
'core/ext/'
);
$parts = explode('\\', $class_name);
// Set the class file name.
$file_name = end($parts).'.php';
foreach($array_directories as $path_directory){
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path_directory),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $fileObject) {
if ($fileObject->isDir()) {
$files[] = str_replace('\\', '/', $fileObject->getPathname()).'/';
}
}
}
$array_directories = array_merge($array_directories,$files);
// Loop the array.
foreach($array_directories as $path_directory){
if(file_exists(WEBSITE_DOCROOT.$path_directory.$file_name)){
include WEBSITE_DOCROOT.$path_directory.$file_name;
}
}
}
spl_autoload_register('autoload_multiple_directory');
The error line is pointing to new RecursiveDirectoryIterator($path_directory), why?
I must use absolute path in new RecursiveDirectoryIterator(WEBSITE_DOCROOT.$path_directory) as the init.php is called via ajax sometimes.

Categories