Excel is not exporting using php office in Laravel - php

I am using PHPOffice for exporting excel in laravel it work fine on localhost but it gives me internal server error on live server error?
public function export(Request $request){
$branchId = $this->decryption($request->branch_id);
$data = Reservation::select("id", "name", "contact","start_time","end_time","target_date",'weekdays')->with('pages',function($query){
$query->select('pages.id','name');
})->when($request->has('start_date'),function($query) use ($request){
$query->where('target_date','>=',$request->start_date);
})->when($request->has('end_date'),function($q) use ($request){
$q->where('target_date','<=',$request->end_date);
})
->where('branch_id',$branchId)->get();
$data_array [] = array("name","contact","target_date","start_time","end_time","weekdays","page");
foreach($data as $data_item)
{
$data_array[] = array(
'name' =>$data_item->name,
'contact' => $data_item->contact,
'target_date' => $data_item->target_date,
'start_time' => $data_item->start_time,
'end_time' => $data_item->end_time,
'weekdays' => implode($data_item->weekdays),
'page' =>$data_item['pages'][0]['name']
);
}
$this->ExportExcel($data_array);
}
This funciton is used to export data which we have got from export function
public function ExportExcel($customer_data){
ini_set('max_execution_time', 0);
ini_set('memory_limit', '4000M');
try {
$spreadSheet = new Spreadsheet();
$spreadSheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(20);
$spreadSheet->getActiveSheet()->fromArray($customer_data, NULL, 'A1');
$Excel_writer = new Xls($spreadSheet);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Customer_ExportedData.xls"');
header('Cache-Control: max-age=0');
ob_end_clean();
$Excel_writer->save('php://output');
exit();
} catch (Exception $e) {
return $e;
}
}`
This is what i am getting error at the end in respose
status code :502
{
"message": "Internal server error"
}

Related

Using the Google Drive API for PHP, What is the proper way to upload a file while setting the "keepRevisionForever" to true?

I am trying to allow file uploads to overwrite the previous copy and keep the revision history permanent within Google Drive. Also...Do I need to upload with a set ID or is the file name going to overwrite natively?
Here is a sample of what I have as a test function:
function uploadFile($filename = "")
{
$title="testFile";
$description="Testing the upload of the file";
$mimeType="image/jpeg";
$filename = ROOTPATH."IMG_1232.JPG"; //Temporarily overriding $filename for testing.
$file = new Google_Service_Drive_DriveFile();
$file->setName($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$this->startGDService();
$createdFile = $this->service->files->create($file, array(
'data' => $data,
'mimeType' => $mimeType,
'keepRevisionForever' => true // <---This doesn't seem to work.
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return;
}
Looks like I was using the wrong function. The create function will always create a file on the drive. To overwrite a particular file, you need to use the update() function. See here:
function updateFile($filename, $fileID)
{
$this->startGDService();
$filename = UPLOAD_PATH.$filename;
$mimetype = mime_content_type ($filename);
try {
$emptyFile = new Google_Service_Drive_DriveFile();
$data = file_get_contents($filename);
$this->service->files->update($fileID, $emptyFile, array(
'data' => $data,
'mimeType' => $mimetype,
'uploadType' => 'multipart',
'keepRevisionForever' => true
));
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}

problem with maatwebsite/excel and \DB::commit();

Im trying store some data in db, and immediately after i'm triying to download and excel file with that data. So I've notice that excel package block my commit, and obviusly it doesnt allow me to store data in DB. This is my code.
- I'm using Laravel 5.5
-"maatwebsite/excel": "~2.1.0",
public function refundTicketAndGenerateExcel($transactions, $table)
{
try
{
\DB::beginTransaction();
$this->storeRefundData($transactions);
$response = $this->generateExcel($table);
\DB::commit();
return $response;
}
catch (\Exception $e)
{
\DB::rollback();
\Log::error($e);
$result['message'] = $e->getMessage();
return response()->json($result, 500);
}
}
public function generateExcel($table)
{
Excel::create('Reembolsos', function ($excel) use ($table) {
$excel->sheet('Reembolsos', function ($sheet) use ($table) {
$FontStyle = array(
'font' => array(
'name' => 'Arial',
'color' => array('rgb' => '000000'),
'size' => 11
),
);
$sheet->loadView($this->path . '.partials.excel', ['table'=>$table]);
$sheet->getStyle('A1:K1000')->applyFromArray($FontStyle);
});
})->export('xls');
}
PD: If I just comment \DB::beginTransaction() and \DB::commit(), everything works fine; On the other hand if I just comment Excel::create block, everything works fine too; That's why I sait that excel package blocks my commit.
Thanks in advance.
When you call export(), it kills your script. Pretty lame design to be honest:
protected function _download(Array $headers = [])
{
$filename = $this->filename;
$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
// Just for Microsoft Explore
if (preg_match('/Trident|Edge/i', $userAgent)) {
$filename = rawurlencode($filename);
}
// Set the headers
$this->_setHeaders(
$headers,
[
'Content-Type' => $this->contentType,
'Content-Disposition' => 'attachment; filename="' . $filename . '.' . $this->ext . '"',
'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past
'Last-Modified' => Carbon::now()->format('D, d M Y H:i:s'),
'Cache-Control' => 'cache, must-revalidate',
'Pragma' => 'public'
]
);
// Check if writer isset
if (!$this->writer)
throw new LaravelExcelException('[ERROR] No writer was set.');
// Download
$this->writer->save('php://output');
// End the script to prevent corrupted xlsx files
exit;
}
https://github.com/Maatwebsite/Laravel-Excel/blob/2.1/src/Maatwebsite/Excel/Writers/LaravelExcelWriter.php#L347-L377
Fix this by returning the writer object that Excel::create() returns, and remove the ->export() part.
$writer = Excel::create(blah blah blah); // no->export() now!
return $writer;
Then do the export affter your commit.
$writer = $this->generateExcel($table);
\DB::commit();
return $writer->export();

How to share file for anyone Google Drive API using PHP

I have been trying over and over, but could not reach any result.
the code is generating permission id and I don't know what that means.
Please do help if anyone succeeded in this before, I just want to share file publicly using the google drive api v2.0
$fileId = '18mWN0UWX_z-4A1gag85ou0Im-wvKfMZU-tibdVd8nxY';
$userPermission = new Google_Service_Drive_Permission(array(
'type' => 'anyone',
'role' => 'reader',
'emailAddress' => 'user#example.com'
));
$request = $service->permissions->create(
$fileId, $userPermission, array('fields' => 'id'));
$batch->add($request, 'user');
$domainPermission = new Google_Service_Drive_Permission(array(
'type' => 'domain',
'role' => 'reader',
'domain' => 'example.com'
));
$request = $service->permissions->create(
$fileId, $domainPermission, array('fields' => 'id'));
$batch->add($request, 'domain');
$results = $batch->execute();
foreach ($results as $result) {
if ($result instanceof Google_Service_Exception) {
// Handle error
printf($result);
} else {
printf("Permission ID: %s\n", $result->id);
}
}
} finally {
$service->getClient()->setUseBatch(false);
}
Here is my code snippet which was 2 years old.
$uplodedOriginalFile = new Google_Service_Drive_DriveFile();
$originallinkdata = file_get_contents($downloadlink['originallink']);
$uploadedfile = $service->files->insert($uplodedOriginalFile, array(
'data' => $originallinkdata,
'uploadType' => 'multipart',
));
$newPermission = new Google_Service_Drive_Permission();
//$newPermission->setValue($value);
$newPermission->setType('anyone');
$newPermission->setRole('reader');
try
{
$service->permissions->insert($uploadedfile['id'], $newPermission);
}
catch (Exception $e)
{
print "An error occurred: " . $e->getMessage();
}
$publicOriginallink = "https://googledrive.com/host/".$uploadedfile['id'];
So you just need the inserted file Id and keep the permssion for anyone as reader and append the inserted file Id after "https://googledrive.com/host/ [newly inserted file id which is returned by google drive sdk]"
code snippet worked
$fileid =$createdFile['id'];
//--insert permission to file in public
$newPermission = new Google_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
try
{$service->permissions->insert($fileid, $newPermission);}
catch (Exception $e){print "An error occurred: " . $e->getMessage();}
$publicOriginallink = "https://googledrive.com/host/".$fileid;
I just made few changes with Jai's code (Google_Permission) to match with my Google APIs Client Library version.

Google API PHP Update File

I'm trying to update the content of the file. Use the PHP function:
function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
try {
// First retrieve the file from the API.
$file = $service->files->get($fileId);
// File's new metadata.
$file->setTitle($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);
// File's new content.
$data = file_get_contents($newFileName);
$additionalParams = array(
'newRevision' => $newRevision,
'data' => $data,
'mimeType' => $newMimeType
);
// Send the request to the API.
$updatedFile = $service->files->update($fileId, $file, $additionalParams);
return $updatedFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
....
$data = retrieveAllFiles($service);
$fileName = 'test.txt';
$mimeType = mime_content_type('./'.$fileName);
$res = updateFile($service, $data[0]['id'], $data[0]['title'], 'update', $mimeType, $fileName, true);
I'm trying to add a text file line "test string". Function updates the data file (description, lastModifyingUser...), but the content of the file remains the same. Who can tell what's wrong?
In additionalParams need to add :
'uploadType' => 'multipart',
or
'uploadType' => 'media',
Hope it helps!

How do I download a file with php and the Amazon S3 sdk?

I'm trying to make it so that my script will show test.jpg in an Amazon S3 bucket through php.
Here's what I have so far:
require_once('library/AWS/sdk.class.php');
$s3 = new AmazonS3($key, $secret);
$objInfo = $s3->get_object_headers('my_bucket', 'test.jpg');
$obj = $s3->get_object('my_bucket', 'test.jpg', array('headers' => array('content-disposition' => $objInfo->header['_info']['content_type'])));
echo $obj->body;
This just dumps out the file data on the page. I think I need to also send the content-disposition header, which I thought was being done in the get_object() method, but it isn't.
Note: I'm using the SDK available here: http://aws.amazon.com/sdkforphp/
Both of these methods work for me. The first way seems more concise.
$command = $s3->getCommand('GetObject', array(
'Bucket' => 'bucket_name',
'Key' => 'object_name_in_s3'
'ResponseContentDisposition' => 'attachment; filename="'.$my_file_name.'"'
));
$signedUrl = $command->createPresignedUrl('+15 minutes');
echo $signedUrl;
header('Location: '.$signedUrl);
die();
Or a more wordy but still functional way.
$object = $s3->getObject(array(
'Bucket' => 'bucket_name',
'Key' => 'object_name_in_s3'
));
header('Content-Description: File Transfer');
//this assumes content type is set when uploading the file.
header('Content-Type: ' . $object->ContentType);
header('Content-Disposition: attachment; filename=' . $my_file_name);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
//send file to browser for download.
echo $object->body;
Got it to work by echo'ing out the content-type header before echo'ing the $object body.
$objInfo = $s3->get_object_headers('my_bucket', 'test.jpg');
$obj = $s3->get_object('my_bucket', 'test.jpg');
header('Content-type: ' . $objInfo->header['_info']['content_type']);
echo $obj->body;
For PHP sdk3 change the last line of Maximus answer
$object = $s3->getObject(array(
'Bucket' => 'bucket_name',
'Key' => 'object_name_in_s3'
));
header('Content-Description: File Transfer');
//this assumes content type is set when uploading the file.
header('Content-Type: ' . $object->ContentType);
header('Content-Disposition: attachment; filename=' . $my_file_name);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
//send file to browser for download.
echo $object["Body"];
If you're still looking for a relevant answer in 2019+, With AWS SDK for PHP 3.x and specifically '2006-03-01' with composer, the following worked for me
...
/**
* Download a file
*
* #param string $object_key
* #param string $file_name
* #return void
*/
function download($object_key, $file_name = '') {
if ( empty($file_name) ) {
$file_name = basename($file_path);
}
$cmd = $s3->getCommand('GetObject', [
'Bucket' => '<aws bucket name>',
'Key' => $object_key,
'ResponseContentDisposition' => "attachment; filename=\"{$file_name}\"",
]);
$signed_url = $s3->createPresignedRequest($cmd, '+15 minutes') // \GuzzleHttp\Psr7\Request
->getUri() // \GuzzleHttp\Psr7\Uri
->__toString();
header("Location: {$signed_url}");
}
download('<object key here>', '<file name for download>');
NOTE: This is a solution for those who would want to avoid the issues that may arise from proxying the download through their servers by using a direct download link from AWS.
I added the Content-Disposition header to the getAuthenticatedUrl();
// Example
$timeOut = 3600; // in seconds
$videoName = "whateveryoulike";
$headers = array("response-content-disposition"=>"attachment");
$downloadURL = $s3->getAuthenticatedUrl( FBM_S3_BUCKET, $videoName, FBM_S3_LIFETIME + $timeOut, true, true, $headers );
This script downloads all files in all directories on an S3 service, such as Amazon S3 or DigitalOcean spaces.
Configure your credentials (See the class constants and the code under the class)
Run composer require aws/aws-sdk-php
Assuming you saved this script to index.php, then run php index.php in a console and let it rip!
Please note that I just wrote code to get the job done so I can close down my DO account. It does what I need it to, but there are several improvements I could have made to make it more extendable. Enjoy!
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
class DOSpaces {
// Find them at https://cloud.digitalocean.com/account/api/tokens
const CREDENTIALS_API_KEY = '';
const CREDENTIALS_API_KEY_SECRET = '';
const CREDENTIALS_ENDPOINT = 'https://nyc3.digitaloceanspaces.com';
const CREDENTIALS_REGION = 'us-east-1';
const CREDENTIALS_BUCKET = 'my-bucket-name';
private $client = null;
public function __construct(array $args = []) {
$config = array_merge([
'version' => 'latest',
'region' => static::CREDENTIALS_REGION,
'endpoint' => static::CREDENTIALS_ENDPOINT,
'credentials' => [
'key' => static::CREDENTIALS_API_KEY,
'secret' => static::CREDENTIALS_API_KEY_SECRET,
],
], $args);
$this->client = new S3Client($config);
}
public function download($destinationRoot) {
$objects = $this->client->listObjectsV2([
'Bucket' => static::CREDENTIALS_BUCKET,
]);
foreach ($objects['Contents'] as $obj){
echo "DOWNLOADING " . $obj['Key'] . "\n";
$result = $this->client->getObject([
'Bucket' => 'dragon-cloud-assets',
'Key' => $obj['Key'],
]);
$this->handleObject($destinationRoot . $obj['Key'], $result['Body']);
}
}
private function handleObject($name, $data) {
$this->ensureDirExists($name);
if (substr($name, -1, 1) !== '/') {
echo "CREATING " . $name . "\n";
file_put_contents($name, $data);
}
}
private function ensureDirExists($name) {
$dir = $name;
if (substr($name, -1, 1) !== '/') {
$parts = explode('/', $name);
array_pop($parts);
$dir = implode('/', $parts);
}
#mkdir($dir, 0777, true);
}
}
$doSpaces = new DOSpaces([
'endpoint' => 'https://nyc2.digitaloceanspaces.com',
'credentials' => [
'key' => '12345',
'secret' => '54321',
],
]);
$doSpaces->download('/home/myusername/Downloads/directoryhere/');

Categories