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:
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
.
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
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';