Skip to content

Instantly share code, notes, and snippets.

@ganey
Last active November 10, 2015 14:24
Show Gist options
  • Save ganey/2554f349129fb0817ce7 to your computer and use it in GitHub Desktop.
Save ganey/2554f349129fb0817ce7 to your computer and use it in GitHub Desktop.
Google Api Client PHP Image Upload
<?php
//Based on composer require google/api-client:^1.1
$filename = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
$tmp_name = $_FILES['file']['tmp_name'];
$newurl = '/media/' . $filename;
//get service account credentials here: https://console.developers.google.com/project/APP-NAME/apiui/credential
$credentials = new \Google_Auth_AssertionCredentials(
$service_email,
['https://www.googleapis.com/auth/devstorage.full_control'],
file_get_contents('/path/to/keyfile.p12')
);
$client = new \Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
//these might not be needed:
$client->setApplicationName($appname);
$client->setDeveloperKey($apidevkey);
//set acl
$acl = new \Google_Service_Storage_ObjectAccessControl();
$acl->setEntity('allUsers');
$acl->setRole('READER');
$storage = new \Google_Service_Storage($client);
$file = new \Google_Service_Storage_StorageObject();
$file->setName($newurl);
$file->setAcl($acl);
$file->setContentType($type);
$storage_file = $storage->objects->insert(
BUCKET_NAME,
$file,
['name' => $newurl, 'data' => file_get_contents($tmp_name), 'uploadType' => 'media', 'mimeType' => $type]
);
$accessResult = $storage->objectAccessControls->insert(BUCKET_NAME, $storage_file->getName(), $acl);
$image_href_url = $storage_file->getMediaLink();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment