Tag Archives: Google Cloud Storage

Google Cloud Storage – Set ACL for objects in a bucket

Hi I have been trying to upload files to Google Cloud Storage from my Google App Engine App (PHP) and got stuck when trying to set the ACL for those files. I tried to set the ACL manually in my code at the time of file upload and it was proving to be tricky as my app is using Laravel which is using a different way to handle file uploads.

For people using normal php scripts can use following method given in GCS docs.

 

<?php
use google\appengine\api\cloud_storage\CloudStorageTools;

$object_url = 'gs://my-bucket/'.time().rand(0,1000).'.txt';
$options = stream_context_create(['gs'=&gt;['acl'=&gt;'public-read']]);

$my_file = fopen($object_url, 'w', false, $options);
for($i=0;$i&lt;900;$i++) {
  fwrite($my_file, 'Number '.$i.' - '.rand(0,1000).'\n');
}
fclose($my_file);

$object_public_url = CloudStorageTools::getPublicUrl($object_url, false);

header('Location:' .$object_public_url);

But there is a different, much easier option using GSUTIL tool. With this tool we can give a command on a bucket to set the default ACL for that bucket. So in my case that was public access.

First before giving the command follow steps given in this url to install the gsutil tool.

After installing set up your credentials as per this link.

To setup the connection first run this command:

C:\Python27>python c:\gsutil\gsutil config

Then give the following command.

 

C:\Python27>python c:\gsutil\gsutil defacl set public-read gs://your-bucket-name

This will make all your future uploads public read enabled.

If you want to further learn about gsutil acl commmands you can read up here.

Advertisements