PHP ZipArchive Not Working in Laravel - php

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

Related

Undefind Property Error while creating Zip file in Laravel using ZipArchive

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.

Use Laravel Controller in simple php file

I have simple .php file:
$ffs = glob("*.zip");
foreach($ffs as $ff){
$zip = new ZipArchive;
if ($zip->open($ff) === TRUE) {
$zip->extractTo('./');
$zip->close();
}
*RUN METHOD FROM LARAVEL CONTROLLER OUTSIDE APP DIR*
}
Now I want to run controller method from Laravel. Is this possible?

PSR-4 autoloading issue

Problem:
I have the following file structure
-api (contains index.php)
--src
---vendor
----auth (contains auth.php)
----bin
----composer
----nesbot
----rbdwllr
----sympfony
here is my composer.json
{
"autoload": {
"psr-4": {
"AuthSpace\\": "/auth",
"Tests\\": "/rbdwllr/reallysimplejwt/tests",
"Symfony\\Polyfill\\Mbstring\\": "/symfony/polyfill-mbstring",
"Symfony\\Component\\Translation\\": "/symfony/translation",
"ReallySimpleJWT\\Helper\\": "/rbdwllr/reallysimplejwt/src/Helper",
"ReallySimpleJWT\\Exception\\": "/rbdwllr/reallysimplejwt/src/Exception",
"ReallySimpleJWT\\": "/rbdwllr/reallysimplejwt/src",
"": "/nesbot/carbon/src"
}
}
}
index.php
require __DIR__ . '/src/vendor/autoload.php';
$argument1 = $_GET['argument1'];
$tokenCode = $_GET['tokenCode'];
include 'config/database.php';
include 'objects/program1.php';
include 'auth.php';
use ReallySimpleJWT\Token;
use Carbon\Carbon;
$secret = "somesecret";
if (($_SERVER['REQUEST_METHOD']) == "GET") {
if ($_GET['url'] == "bankquery") {
if($tokenCode===NULL){
echo "no correct token provided";
print($results);
} else {
$results = Token::validate($tokenCode, $secret);
if ($results = 1){
$var = new AuthClass();
$var = AuthClass::checkTime($tokenCode);
} else {
echo "no correct token provided";
}
}
} else {
echo "some GET other query";
}
?>
auth.php
<?php namespace AuthSpace;
use ReallySimpleJWT\Token;
use Carbon\Carbon;
class AuthClass{
public static function checkTime($tokenCode){
// getting payload from token code by accessing the composer dependency method in a class Token
$received = Token::getPayload($tokenCode);
return $received;
}}
?>
I've generated the autoload using composer dump-autoload, checked the prs4 links - they all seem to show correct directory and namespace linking.
But nontheless, after running index.php file i keep getting the following error, but don't know why.
PHP Fatal error: Uncaught Error: Class 'AuthSpace\AuthClass' not
found

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

How can I access my class properties from a namespace with php version 5.5.12?

I'm using WAMPSERVER 2.5 and PHP version 5.5.12 on Windows 8 PC. I created a namespace which worked ok when I was running PHP version 5.2.12. After upgrading to php version 5.5.12 I'm getting error message about undefined variables which I think means that the namespace is not being used. Here's what my code looks like:
In my UploadFile.php file I have this:
<?php
namespace myNamespace;
class UploadFile
{
protected $avatarUrl;
public function getUrl()
{
return $this->avatarUrl;
}
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
echo $file[$key];
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$url='http://westcoastchill.com/dc-esports/images/' . $filename;
$this->avatarUrl=$url;
...
}
.....
?>
Then here's the html form that uses the class in the namespace where I get the error messages that states that the variable 'newUrl' is undefined and the index 'displaymax' is undifined.
<?php
require_once 'uploads/src/myNamespace/UploadFile.php';//<------names here
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']); //<------ undifined index
}
$max = 50 * 1024;
$result = array();
if (isset($_POST['upload'])) {
$destination = __DIR__ . '/uploads/uploaded/';
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
$upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
$newUrl=$upload->getUrl(); //<----------- here's the undifined newUrl;
} catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
$oldUrl=$newUrl;
...
?>
}
How can I access my class from a namespace with php version 5.5.12?
Thanks for any help with this!
UPDATE: Sorry I had getUrl() outside of superclass but in my actual project is in the correct place. So I tried:
\myNamespace\UploadFile::convertToBytes(ini_get('post_max_size'));...
but I still get the same error. I also tried adding use:
myNamespace\UploadFile and \myNamespace\UploadFile...
still getting the same error message. The thing is my code worked with the using statement before I updated PHP so I'm curious why just an update would change things.
UploadFile class is within the namespace myNamespace, so to reference the class from outside of myNamespace, you would need to use \myNamespace\UploadFile.
If you are already in the global namespace, you don't need the leading slash, but I think it's good practice to always use the leading slash, since the leading slash refers to the global namespace.
Ex:
$_SESSION['postmax'] = \myNamespace\UploadFile::convertToBytes(ini_get('post_max_size'));
and
$upload = new \myNamespace\UploadFile($destination);
The issue was the configuration of the php.ini file. After researching more I tried turning off 'display_errors=Off in the php.ini file and the code the code ran using the namespace and everything. Conclusion: the php.ini file of the new installation different settings. I'll explore the settings more but my problem was solved by turning off error displaying. Obviously this is not a desired option so I'll toggle on and off as I go forward and read up on other parameters in the file that may help me.

Categories