I need to update the ACL basically by adding or removing the allUsers entity.
I have the PHP library and what I'm doing at moment is:
$storage = new StorageClient([
'projectId' => "xxxxx",
'keyFilePath' => mykey,
]);
$bucket = $storage->bucket('mybucket');
$acl = $bucket->acl('objectAccessControls', 'path/file/on/bucket');
if(add){
$acl->add('allUsers', 'READER');
}else{
$acl->delete('allUsers');
}
With this code actually changes ALL bucket configuration, not the file only.
How can I correctly specify the path of a specific file and change permissions only on path/file/on/bucket? I'm using the wrong functions?
Here the documentation that I'm using
https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.90.0/storage/acl
This is the case if add:
This is the else case:
UPDATE 1:
Using this to delete seems working -> https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/delete
Tried to include the parameters listed here to the call I do, something like this:
$options = ['object' => 'path/obj'];
$acl->delete('allUsers', $options)
Still not working
Actually I've solved by using the Google_Service
$client = new Google_Client();
$client->setApplicationName('GoogleBuck/0.1');
$client->useApplicationDefaultCredentials(); // app engine env
$client->addScope('https://www.googleapis.com/auth/devstorage.full_control');
$storage = new Google_Service_Storage($client);
$acl = new Google_Service_Storage_ObjectAccessControl($client);
$acl->setEntity('allUsers');
$acl->setRole('READER');
$acl->setBucket($bucketName);
$acl->setObject($objectName);
To add
$response = $storage->objectAccessControls->insert($bucketName, $objectName, $acl);
To delete
$response = $storage->objectAccessControls->delete($bucketName, $objectName, 'allUsers');
Related
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.
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
);
i am new in firebase web if it possible to upload, download, and delete file using php. i have upload file using JS but i want to download using PHP.
Here is script of download file using JS but i want in PHP.
Thanks in advance...
My Code
[START storage_quickstart]
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Storage\StorageClient;
# Your Google Cloud Platform project ID
$projectId = 'My project ID';
# Instantiates a client
$storage = new StorageClient([
'projectId' => $projectId
]);
# The name for the new bucket
$bucketName = 'my bucket';
# Creates the new bucket
$bucket = $storage->createBucket($bucketName);
echo 'Bucket ' . $bucket->name() . ' created.';
# [END storage_quickstart]
return $bucket;
The short answer is that you should use gcloud-php. This requires that you set up a service account (or use Google Compute Engine/Container Engine/App Engine which provide default credentials).
It's likely that you'll create a service account, download a keyfile.json, and provide it as an argument to the StorageClient, like so:
# Instantiates a client
$storage = new StorageClient([
'keyFilePath' => '/path/to/key/file.json',
'projectId' => $projectId
]);
Alternatively, it looks like they've built another layer of abstraction, which takes the same arguments but allows you to use lots of other services:
use Google\Cloud\ServiceBuilder;
$gcloud = new ServiceBuilder([
'keyFilePath' => '/path/to/key/file.json',
'projectId' => 'myProject'
]);
$storage = $gcloud->storage();
$bucket = $storage->bucket('myBucket');
That's an old question, but I was struggling with same problem... hope my solution help someone.
In fact, I really don't know if there is an official way to do that, but I created the method below and it worked for me.
function storageFileUrl($name, $path = []) {
$base = 'https://firebasestorage.googleapis.com/v0/b/';
$projectId = 'your-project-id';
$url = $base.$projectId.'/o/';
if(sizeof($path) > 0) {
$url .= implode('%2F', $path).'%2F';
}
return $url.$name.'?alt=media';
}
To access files in the root of bucket:
$address = storageFileUrl('myFile');
Result: https://firebasestorage.googleapis.com/v0/b/your-project-id.appspot.com/o/myFile?alt=media
To access files inside some folder, do:
$address = storageFileUrl('myFile', ['folder', 'subfolder']);
Result: https://firebasestorage.googleapis.com/v0/b/your-project-id.appspot.com/o/folder%2Fsubfolder%2FmyFile?alt=media
Enjoy.
Using the code below
define('DRIVE_SCOPE', 'https://www.googleapis.com/auth/drive');
define('SERVICE_ACCOUNT_EMAIL', 'xxx.iam.gserviceaccount.com');
define('SERVICE_ACCOUNT_PKCS12_FILE_PATH', 'xxx');
function buildService($userEmail) {
$key = file_get_contents(SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_Auth_AssertionCredentials(
SERVICE_ACCOUNT_EMAIL,
array(DRIVE_SCOPE),
$key);
//$auth->sub = $userEmail;
$client = new Google_Client();
$client->setAssertionCredentials($auth);
return new Google_Service_Drive($client);
}
$service = buildService('xxx.apps.googleusercontent.com');
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'Invoices',
'mimeType' => 'application/vnd.google-apps.folder'
));
$file = $service->files->create($fileMetadata, array(
'fields' => 'id'
));
printf("Folder ID: %s\n", $file->id);
I have been trying to create a folder on my drive account through PHP. I believe everything is configured correctly and I am getting a result
Folder ID: 0B2nllBpB_k0NQWFNUjlSc0NUdE0
But the folder is not being created on my drive account. The same goes with creating files as well. It keeps returning an ID but nothing is actually created. What exactly am I doing wrong?
Your current code is authenticating as the service account and creating a file. The resultant file would then only be accessible to the service account, not your Google user. You can confirm this by doing a list of files instead of a create in your code, you'll get back the files you've previously created.
Your code has sub= commented out. Uncommented that line and make sure you've followed the domain-wide delegation instructions so that your code can authenticate and act as your Google user.
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