Laravel socialite facebook avatar - php

Im using Laravel 5.2 with Socialite. I am able to pull out the details of the user but the problem is that the avatar is not being displayed properly if I inject it on its src.
Socialite returns an object wherein I could use it as $facebookDetails->getAvatar() in which returns a value of like this https://graph.facebook.com/v2.6/123456789/picture?type=normal
If I echo this value in the image src, it would look like this.
<img src="https://graph.facebook.com/v2.6/123456789/picture?type=normal" />
It seems that this is not the actual URL of the image since when I enter this on the browser, it redirects me to the "actual" image and displays the image.
How could I display the image on the img tag to display the actual image?

Simply fetch the data using file_get_contents function and process the retrieved data.
In Controller
use File;
$fileContents = file_get_contents($user->getAvatar());
File::put(public_path() . '/uploads/profile/' . $user->getId() . ".jpg", $fileContents);
//To show picture
$picture = public_path('uploads/profile/' . $user->getId() . ".jpg");

i'm using following code:
/**
* In order to save the user's avatar
* REMEMBER TO ADD "use File; use Illuminate\Support\Carbon; use DB;" TO TOP!
* #param $avatar Socialite user's avatar ($user->getAvatar())
* #param $userId User's id database
*/
public function saveImageAvatar($avatar, $userId)
{
$fileContents = file_get_contents($avatar);
$path = public_path() . '/users/images/' . $userId . "_avatar.jpg";
File::put($path, $fileContents);
DB::table('Images')->insert(
['path' => $path,
'nome' => 'avatar',
'users_id' => $userId,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s')]);
}

Related

How to open the PDF generated in new tab

I have a Leave application project that generates a PDF file.
this is the code that generates the pdf after I click submit.
$id = DB::table('leave')->where('user_id', auth()->user()->id)->max('id');
$data = leave::where('id', $id)->select('*')->get();
$filename = auth()->user()->name." - S - ". "LEAVE - ".$randomString->randomString(8)."-".$request->filing_date.".pdf";
$path = storage_path('app/leave_file/'.$filename);
PDF::loadView('pdf_views.leave_pdf', $data[0])->setPaper('legal')->save($path);
if(file_exists($path)){
DB::table('leave_files')->insert([
'filename' => $filename,
'leave_id' => DB::table('leave')->where('user_id', auth()->user()->id)->max('id'),
]);
}
return redirect()->route('leave')->with('success', "success");
I wonder if I can make the newly generated pdf open in the new tab after I click submit on my leave application. thank you to anyone who can help
According to the Laravel docs this is what you need: https://laravel.com/docs/9.x/responses#file-responses
File Responses
The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
Use the Cache Facade, to store the generated pdf temporary.
$uuid = Str::uuid();
return response()->stream(function () use ($uuid) {
echo Cache::remember($uuid, 300, function() {
return 'genertated pdf content'
});
}, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => sprintf('attachment; filename=%s;', $uuid),
]);
Create a route to access to cached file. Name the route.
Now you can open it in a new tab from you frontend e.g. Generate the route with route('routename', ['param' => 123]) and pass it to your FE with a REST endpoint for example.
window.open(url,'_blank');

Request $request convert to Array $data

I'm new at laravel and i was reading the document for a week now. i was working on crud about modification of register form i'm almost finish but then i bump in to this problem which is now i'm trying to look for a right syntax on my question would be how to i check and move a file use as a parameter to store and create a path folder for the image. similar to the code below i show using Request. cause if you look at the register page controller at the create function the parameter used is array.
tried reading documents and research couldn't find any or maybe i lack of keywords to direct me into this type of problem.
I have this code and this is right
public function store(Request $Request)
{
$ProfileUser = new User();
if($Request->hasfile('Img1'))
{
$file = $Request->file('Img1');
$extension = $file->getClientOriginalExtension(); // Get Image Ext.
$filename = time() . "." . $extension;
$file->move('uploads/employee/', $filename);
$ProfileUser->image1 = $filename;
} else
{
return $Request;
$ProfileUser->image1 = 'no image';
}
$ProfileUser->fname = $Request->input('fname');
$ProfileUser->mname = $Request->input('mname');
$ProfileUser->lname = $Request->input('lname');
$ProfileUser->homeaddress = $Request->input('homeaddr');
$ProfileUser->mobilenum = $Request->input('mobilenum');
$ProfileUser->accounttype = $Request->input('typeAcc');
$ProfileUser->image1 = $Request->input('img1');
$ProfileUser->save();
return redirect()->route('home');
}
but then i also have this modification in make:auth i made and added columns
this is my problem here since the function is using an array instead of the Request.
protected function create(array $data) <-- this is the Error
{
if($data->hasFile('image1')) { <-- from here to:
$file = $data->file('image1');
$extension = $file->getClientOriginalExtension(); // Get Image Ext.
$filename = time() . "." . $extension;
$file->move('uploads/employee/', $filename);
} else {
return $request;
} <-- here this function
$user = User::create([
'name' => $data['fname'] . " " . $data['lname'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'fname' => $data['fname'],
'mname' => $data['mname'],
'lname' => $data['lname'],
'homeaddress' => $data['homeaddr'],
'mobilenum' => $data['mobilenum'],
'accounttype' => $data['typeAcc'],
'image1' => $data['image1']
]);
return $user;
}
if i commend out the file validation the create function work fine and is able to save to database but then i need the image to be move on the 1st function it works perfect but in the 2nd using a parameter array doesn't i know i have maybe a wrong syntax which i ask for now how. and if it's ok can you guys explain a bit about the difference between Request vs Array? that i may able also to understand both
The $Request variable contains an object from the Laravel Request class (Illuminate \ Http \ Request). Read more about here
An Array is a PHP data structure. Read about arrays in PHP here.
To get all request's data as an array, you can call the method all() on the request object. It will give you an associative array.
$request->all();

Upload PDF file on Google Cloud Storage with mpdf library

I am using mpdf library to convert HTML to PDF and successfully stored my pdf file on local as well as remote server. But I don't want to store my pdf files on my code repos on server and like to utilize storage bucket available on google cloud.
/*
*/
private function generatePDF($params, $quotationId) {
$location = '/var/www/html/development/pdfs/';
$html = $this->load->view('quotation', $data, TRUE);
$filename = "quo_" .time() . ".pdf";
$mpdf = new \Mpdf\Mpdf(['mode' => 'en-IN', 'format' => 'A4']);
$mpdf->WriteHTML($html);
$mpdf->SetHTMLFooter('<p style="text-align: center; text-size: 12px;">This is computer generated quotation. It does not require signature.</p>');
$pdf = $mpdf->Output($location . $filename, 'F');
$this->UploadModel->upload($pdf, $filename);
}
public function upload($pdf, $pdfName) {
$storage = new StorageClient();
$bucket = $storage->bucket("bucketname");
$object = $bucket->upload($pdf, ['name' => $pdfName]);
$object = $bucket->object($pdfName);
$object->update(['acl' => []], ['predefinedAcl' => 'PUBLICREAD']);
}
Here I have used 'F' type in which it saves the pdf file in pdfs folder created in my code repo hosted on cloud server but I would like to directly store it to Google cloud storage bucket.
I am not having much experience about google cloud and mpdf library so looking for help and guidance to achieve the functionality.
Please kindly help me.
I see you are using Cloud Storage Client Libraries for PHP.
First, you need to install it to your machine:
composer require google/cloud-storage
And then you need to set up authentication by following the guide.
Once these are set create a bucket to store the PDFs.
Then replace your upload function with the code from the documentation:
use Google\Cloud\Storage\StorageClient;
/**
* Upload a file.
*
* #param string $bucketName the name of your Google Cloud bucket.
* #param string $objectName the name of the object.
* #param string $source the path to the file to upload.
*
* #return Psr\Http\Message\StreamInterface
*/
function upload_object($bucketName, $objectName, $source)
{
$storage = new StorageClient();
$file = fopen($source, 'r');
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload($file, [
'name' => $objectName
]);
printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}
i also faced same issue & came out with this solution, i hope it will help you.
use 'S' instead of 'F'parameter, so it will return string data & pass this data directly into upload method.

Store S3 URL in database table

I'm building a small asset management system in Laravel 5.2
A user can upload images, video etc to the app and the asset meta data gets stored in the assets table. While that's happening, the asset is renamed to match the asset id (I'm storing the original filename too), I'm storing the mime type and uploading the file to S3.
Where I've come unstuck is storing the S3 url in database.
This is my method
public function store(AssetRequest $request)
{
// Initialise new asset and set the name
// from the form
$asset = new Asset(array(
'name' => $request->get('name')
));
$asset->user_id = Auth::user()->id;
// save the asset to the db
$asset->save();
// set the file var = form input
$file = $request->file('asset_path');
$extension = $file->getClientOriginalExtension();
// modify the asset name
$assetFile = $asset->id . '.' . $request->file('asset_path')->getClientOriginalExtension();
// push the new asset to s3
Storage::disk('s3')->put('uploads/' . $assetFile, file_get_contents($file));
$asset->mime = $file->getClientMimeType();
$s3Url = Storage::url($file);
$asset->s3_url = $s3Url;
$asset->original_filename = $file->getClientOriginalName();
$asset->filename = $assetFile;
$asset->file_extension = $extension;
// return ok
$asset->save();
return \Redirect::route('asset.create')->with('message', 'Asset added!');
}
The lines relating to my attempt at storing the S3 url
$s3Url = Storage::url($file);
$asset->s3_url = $s3Url;
Only seems to store a temporary path /storage//tmp/php8su2r0 rather than an actual S3 url. I'd like to avoid having to set the bucket manually, rather hoping I can use what is configured in config/filesystem.php
Any ideas?
you can get everything from the config using the config(key) function helper
so to get the s3 public url of file, do this:
function publicUrl($filename){
return "http://".config('filesystems.disks.s3.bucket').".s3-website.".config('filesystems.disks.s3.region').".amazonaws.com/".$filename;
}
or you can use the underlying S3Client:(taken from here)
$filesystem->getAdapter()->getClient()->getObjectUrl($bucket, $key);
What your are trying to achieve, I have been doing that in many projects.
All you need to do is create image_url column in database. And pass the s3 bucket link + the name of the file + the extension.
You should know the bit that is constant for me like : https://s3-eu-west-1.amazonaws.com/backnine8/fitness/events/ then I have the id and the extension. in your case it could be name and extension.
if(Input::get('file')) {
$extension = pathinfo(Input::get('filename'), PATHINFO_EXTENSION);
$file = file_get_contents(Input::get('file'));
$s3 = AWS::get('s3');
$s3->putObject(array(
'ACL' => 'public-read',
'Bucket' => 'backnine8',
'Key' => '/fitness/events/'.$event->id.'.'.$extension,
'Body' => $file,
));
$event->image_url = 'https://s3-eu-west-1.amazonaws.com/backnine8/fitness/events/'.$event->id.'.'.$extension;
$event->save();
}

How to turn an s3 object string into something useful when using laravel 5.1 filesystem

I'm at a loss. I'm trying to display an object (image.jpg) I successfully have uploaded to my s3 bucket.
I have made sure the file is set to public. I use the Storage::get(); method which the doc says "returns a string of the object". See here:
The get method may be used to retrieve the contents of a given file.
The raw string contents of the file will be returned by the method:
$contents = Storage::get('file.jpg');
And sure enough, when my show method looks like this:
public function show($id)
{
/* Get DB instance */
$resource = Resource::findOrFail($id);
/* Create s3 file path */
$filePath = 'resource-'.$resource->id;
/* Get object in s3 bucket */
$file = Storage::get($filePath);
return view('resource.show', compact('resource', 'file'));
}
It outputs the following below in my view when I do {!! $file !!}
���p�s0wr�4miq �V�Pr�;�-��##���EM����cA.
{����{��1�Whuf��|Ji�{�=3�P� 1�������3�1Y���W���N�/
�Hnt�Ï�[������4����Uԅ�8u�w���XB�r��=F8�ԟȰ�T��T
]���q��:�K~�с�VV�Alv�����7cOV�7�b�`s����M��D�՝�6]�մ���ԕqJ�
X�?���ቿ3��>��甽�_4o�^s�Ӻ|�#�����H9
" " " " " " " " " " " " " " " " " " " " " " " " "
" " " " " " " " " " " " " " " " " " " " " " " " " " " " " "
Just much, much longer. This isn't useful. How do I convert this into the original image? And is the process the same when I upload/show video?
Okay, so I made things work, but I am in no way sure if this is the smartest way. But hey, it's a step of the way.
Note this solution lets anyone, authenticated or not, access your s3 objects url. I haven't figured out how to control access yet.
Useful resources
The flysystem original documentation
Detailed information about the flysystem package, and describes methods such as getMimetype not covered in the laravel documentation.
Laravel docs
Useful for getting started with the laravel implementation of flysystem.
The AWS Sdk guide for PHP
Good reference if you want to write custom s3 code.
With that out of the way, here is how I create & show s3 objects
1. Add your s3 credentials in config/filesystems.php. I also use s3 for development to make sure things work.
return [
'default' => 's3',
'cloud' => 's3',
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path().'/app',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_REGION'),
'bucket' => env('AWS_BUCKET'),
],
'rackspace' => [
'driver' => 'rackspace',
'username' => 'your-username',
'key' => 'your-key',
'container' => 'your-container',
'endpoint' => 'https://identity.api.rackspacecloud.com/v2.0/',
'region' => 'IAD',
],
],
];
2. My store method: ResourceController#store
Note here that the key is your s3 objects name, and not your aws access key or secret key. Also, if you do not set visibility to 'public' (default is private), this solution won't work e.g. you can't display the file.
public function store(ResourceRequest $request)
{
/* Store entry in DB */
$resource = new Resource();
$resource->title = $request->title;
$resource->save();
/* Prepare data needed for storage */
$key = 'resource-'.$resource->id;
$file = file_get_contents($request->file('resource'));
$visibility = 'public';
/* Store file */
Storage::put($key, $file, $visibility);
/* Success message */
session()->flash('message', $request->title . ' uploaded!');
return redirect()->route('resource-index');
}
3. My show method: ResourceController#show
Here I simply build up the aws s3 objects public url, so I can reference it in my <img> and <video> tags
public function show($id)
{
/* Get DB instance */
$resource = Resource::findOrFail($id);
/* Set bucket */
$bucket = env('AWS_BUCKET');
/* Set file key */
$key = 'resource-'.$resource->id;
/* Build & push s3 url into array */
$file['url']= 'https://s3.eu-central-1.amazonaws.com/'.$bucket.'/'.$key;
/* Get & push mime type into array. */
$file['type'] = Storage::getMimetype($key);
return view('resource.show', compact('resource', 'file'));
}
4. Finally, my view. Here I check for mime type to make sure the right filetype gets the right tag.
#extends('layout.base')
#section('title') Show Resource #stop
#section('content')
<h1>Show Resource</h1>
#include('layout.partials.message')
<h2>{{ $resource->title }}</h2>
#if ($file['type'] == 'image/jpeg')
<img src="{!! $file['url'] !!}" alt="">
#else
<video src="{!! $file['url'] !!}" controls></video>
#endif
#stop
The result
The picture above gets the s3 url: https://s3.eu-central-1.amazonaws.com/bucketname/resource-22
And remember, the flaw is this url is public to anyone. So anyone can go and guess urls until they find the resource they want.
I Hope someone finds this helpful. Now I'll be off to fix that d*mn url access problem...
Try to encode base64 and show img
$file = Storage::get($filePath);
// Read image path, convert to base64 encoding
$imgData = base64_encode($file);
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;
// Echo out a sample image
echo '<img src="'.$src.'">';

Categories