Laravel - How to add image file to Firebase cloud storage? - php

How do I upload images to firebase cloud storage? The documentation gives only these methodes but no upload method. This is the documentation link https://firebase-php.readthedocs.io/en/stable/cloud-storage.html
$storage = $factory->createStorage();
$storageClient = $storage->getStorageClient();
$defaultBucket = $storage->getBucket();
I have seen another stack question related but don't understand the answer.
I would also like to get a link to the stored file.
Thank you in advance!

Check official firebase documentation, as is mentioned there:
"To upload a file to Cloud Storage, you first create a reference to the full path of the file, including the file name."
For example:
// Create a root reference
var storageRef = firebase.storage().ref();
// Create a reference to 'mountains.jpg'
var mountainsRef = storageRef.child('mountains.jpg');
// Create a reference to 'images/mountains.jpg'
var mountainImagesRef = storageRef.child('images/mountains.jpg');
// While the file names are the same, the references point to different files
mountainsRef.name === mountainImagesRef.name // true
mountainsRef.fullPath === mountainImagesRef.fullPath // false
Also, I found another thread here where you can find an example using php

You can do something like this,
$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);
There examples on gcp github repository.
file upload example : here
other examples: here

Related

Picture being uploaded to Firebase storage using PHP but have to create access token manually to make it visible

I am using PHP to upload image to firebase storage. the picture is being uploaded but it is not being accessible as i have to manually create " access token " to make it accessible.
here is the code im using
$bucketName = "example.appspot.com";
$objectName = 'Photos/test.jpeg';
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload(fopen('sign.jpeg', 'r'),
[
'name' => $objectName
]
);
That is indeed working as expected: since your upload is not going through a Firebase SDK, there is not method to generate a download URL.
The common workaround is to create a signed URL with an expiration time far into the future, which is the closest equivalent that Cloud Storage has to Firebase's download URL.
In addition to #Frank's answer, you could also assign the publicRead ACL to the uploaded file and compose the public URL manually:
$bucketName = "example.appspot.com";
$objectName = 'Photos/test.jpeg';
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload(fopen('sign.jpeg', 'r'), [
'name' => $objectName
'predefinedAcl' => 'publicRead'
]);
$publicUrl = "https://{$bucket->name()}.storage.googleapis.com/{$object->name()}";
I have made an indirect way to generate and store the access token.
$payload = file_get_contents('https://firebasestorage.googleapis.com/v0/b/example.appspot.com/o/Photos%2Fpic.jpeg');
$data = json_decode($payload);
echo $data->downloadTokens;
This code has created the access token and it shows the downloadToken on screen.
Thank you everyone for your answers.

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.

how do i upload a file to a directory in google cloud storage using Google_Client library

i want to upload a file to google cloud storage using google client php library on github. Am able to upload file to cloud storage but am not able to upload to a directory in cloud storage. i get the error message No such object: bucketName/abc/test.jpg
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=files/google_cloud.json');
$client->useApplicationDefaultCredentials();
$storage = new Google\Cloud\Storage\StorageClient([
'projectId' => $googleprojectID
]);
$sPath = "files/com/test.jpg";
$objectName = "/abc/test.jpg";
$bucketName = $googlebucketName;
$bucket = $storage->bucket($bucketName);
$bucket->upload( fopen($sPath, 'r') );
$object = $bucket->object($objectName);
$info = $object->update(['acl' => []], ['predefinedAcl' => 'PUBLICREAD']);
First of all, let me share with you this documentation page where you will find the complete reference for the Google Cloud Storage PHP Client Library. More specifically, if you have a look at the upload() method, you will see that in order to set the name of the object uploaded (and therefore its location, given that GCS has a flat namespace), you have to use the options parameter, which can contain a name field pointing to the right location to upload.
Also, note that the correct object name should not start with a slash /, given that it will automatically be added after the bucket name. Therefore, you should modify your code to add something like this:
$sPath = "files/com/test.jpg";
$objectName = "abc/test.jpg"; # Note the removal of "/" here
$options = [
'name' => $objectName
];
$bucketName = $googlebucketName;
$bucket = $storage->bucket($bucketName);
$bucket -> upload(
fopen($sPath, 'r'),
$options
);

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

Creating folder in bucket google cloud storage using php

I am very new to the google cloud storage.
I want to create folder in bucket using php coding. I have searched a quite few sites and on 1 i saw it was written:
"Creating a folder inside a bucket will create a placeholder object named after the directory, has no data content and the mimetype application/x-directory. Directory placeholder objects created in Google Storage Manager are ​not supported."
I could not understand what it is trying to say. How can i create folder please help me out. I tried using the following code:
$req = new Google_HttpRequest("http://commondatastorage.googleapis.com/bucket/myfoldertrial");
$req->setRequestHeaders(array(
'x-goog-project-id' => 21212,
'x-goog-acl' => 'public-read',
'Content-Type' => 'application/x-directory'
));
$req->setRequestMethod('PUT');
$req->setPostBody('myfoldertrial');
I am using the API from following link:
Google API for PHP
Please help me out creating folder using PHP.
You probably don't actually need to create a folder.
Google Storage isn't a tree structure like your operating system's filesystem uses, all Objects are stored in buckets at the top level. However you can give an Object a name with slashes in it, so it will kind of look like it is in a folder - Users/username/docs/2012/09/21/activity.csv is a perfectly good name for an Object and doesn't need any supporting folders.
Once you've got Objects with this sort of scheme in place, you can list them as if you were viewing the contents of a folder with the delimiter and prefix parameters as per these docs.
So if you only wanted to create myfoldertrial so you could upload example.png into it, there's no need to create the folder, you can just upload straight to myfoldertrial/example.png.
Sometimes, in a CMS, you need to create a directory first before able to upload file into it, so the mouse click can trigger an event to take the path as the base folder, then do a batch upload.
It's a file browser, they say.
This code below might help.
<?php
$privateKeyFile = '{{full/path/to/*.p12}}';
$newDirectory = '{{path/of/new/directory/}}'; // remember to end it with a slash.
/**
* Authentication
*/
$client = new Google_Client();
$client->setApplicationName('Create a new folder');
$client->setClientId($clientId);
$scopes = array('https://www.googleapis.com/auth/devstorage.full_control');
$client->setScopes($scopes);
$service = new Google_Service_Storage($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
if (!file_exists($privateKeyFile)) {
die('missing the location of primary key file, given: ' . $privateKeyFile);
}
$key = file_get_contents($privateKeyFile);
$cred = new Google_Auth_AssertionCredentials(
$clientEmailAddress
, $scopes
, $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
/**
* Creating Folder
*/
try {
/* create empty file that acts as folder */
$postBody = new Google_Service_Storage_StorageObject();
$postBody->setName($newDirectory);
$postBody->setSize(0);
$created = $service->objects->insert($bucketName, $postBody, array(
'name' => $newDirectory,
'uploadType' => 'media',
'projection' => 'full',
'data' => '',
));
} catch (Exception $ex) {
echo $ex->getMessage() . "\n<pre>";
print_r($ex->getTraceAsString());
echo '</pre>';
die();
}
echo 'EOF';
You can simply create folder by providing it in a filepath when you are uploading it,
i.e. your url should be https://storage.googleapis.com///?GoogleAccessId=id#developer.gserviceaccount.com&Expires=1410875751&Signature=SIGNATURE

Categories