Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x011/86d4a41af44ed7ff3533 to your computer and use it in GitHub Desktop.
Save x011/86d4a41af44ed7ff3533 to your computer and use it in GitHub Desktop.
<?php
require_once("src/Google/Client.php");
require_once("src/Google/Service/Storage.php");
/**
* Connect to Google Cloud Storage API
*/
$client = new Google_Client();
$client->setApplicationName("App Name");
// $stored_access_token - your cached oauth access token
if( $stored_access_token ) {
$client->setAccessToken( $stored_access_token );
}
$credential = new Google_Auth_AssertionCredentials(
"service account email address",
['https://www.googleapis.com/auth/devstorage.read_write'],
file_get_contents("path/to/private-key-certificate.p12")
);
$client->setAssertionCredentials($credential);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($credential);
// Cache the access token however you choose, getting the access token with $client->getAccessToken()
}
/**
* Upload a file to google cloud storage
*/
$storage = new Google_Service_Storage($client);
$file_name = "what you want your file to be named on Google Cloud Storage";
$obj = new Google_Service_Storage_StorageObject();
$obj->setName($file_name);
$storage->objects->insert(
"bucket name",
$obj,
['name' => $file_name, 'data' => file_get_contents("local path of the file to upload"), 'uploadType' => 'media']
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment