Skip to content

Instantly share code, notes, and snippets.

@AidanThreadgold
Created April 5, 2014 20:25
Show Gist options
  • Save AidanThreadgold/9997654 to your computer and use it in GitHub Desktop.
Save AidanThreadgold/9997654 to your computer and use it in GitHub Desktop.
Upload a file to google cloud
<?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']
);
@dikirill
Copy link

dikirill commented Aug 1, 2016

Thank you for an example.

@askello
Copy link

askello commented Sep 9, 2016

This example works great, thanks! The simplest way to make the upload publicly shared is:

$storage->objects->insert(
    'my_bucket',
    $obj,
    [
        'data'          => file_get_contents($filename),
        'uploadType'    => 'media',
        'mimeType'      => 'image/jpeg',
        'predefinedAcl' => 'publicRead'    // THIS LINE OF CODE MAKES FILE PUBLIC FOR READING
    ]
);

@dchenk
Copy link

dchenk commented Nov 26, 2016

Thanks for this!
Did you have to include the entire Google cloud PHP API library? Or just the two files Client.php and Storage.php? Can I somehow just require those two files?

@sagormax
Copy link

For this library : https://github.com/GoogleCloudPlatform/google-cloud-php#google-cloud-storage-ga
Use as following :

$bucket->upload(
fopen('data3.txt', 'r'), ['predefinedAcl' => 'publicRead']
);

@alcantara64
Copy link

how do i stored the link in db.. to load my contents

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment