I'm using the Google Cloud Platform PHP Client library (https://github.com/google/google-api-php-client) to upload files to a bucket in my project. I need to be able to grab the file using an AJAX request from another domain so therefore need to add the header
Access-Control-Allow-Origin: *
I am pulling my hair out trying to figure this out - my Google searches are fruitless. Code sample for reference:
$client = new Google_Client();
$client->setApplicationName("Test");
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$storage = new Google_Service_Storage($client);
$file_name = "test.txt";
$file_content = "this is a test";
$postbody = array(
'name' => $file_name,
'data' => $file_content,
'uploadType' => "media",
'predefinedAcl' => 'publicRead'
);
$gsso = new Google_Service_Storage_StorageObject();
$gsso->setName( $file_name );
$result = $storage->objects->insert( "my_bucket", $gsso, $postbody );
The file is uploaded correctly and can be viewed in the bucket, but doesn't have the correct headers as I don't know how to add them. In fact, I can't even find a way of adding these headers manually using the Cloud Platform Console. Any pointers appreciated, thanks
So I finally found the documentation I needed, it's only possible to set the CORS configuration for the bucket itself (it is not configurable at file level). Instructions to do so using either gsutil or the XML API are here
I created a cors-json-file.json with contents:
[
{
"origin": ["*"],
"method": ["*"]
}
]
Then ran
gsutil cors set cors-json-file.json gs://my_bucket
It's possible to view the existing CORS configuration for your bucket using
gsutil cors get gs://my_bucket
A full list of configuration options can be found at the Google Bucket API Reference
Whether it's an issue with caching or not I'm unsure, but this seems to work only for files added to the bucket after you make the CORS configuration change, however I'm happy to be corrected on that
You can also configure CORS with PHP using StorageClient in google-cloud-php.
$storage = new StorageClient([
'projectId' => '<project-id>',
'keyFilePath' => '<path-to-key-file>',
]);
$cors = [
[
'maxAgeSeconds' => '3600',
'method' => ['*'],
'origin' => ['*'],
'responseHeader' => ['Content-Type'],
],
]
// Creating a bucket with CORS
$storage->createBucket('<bucket-name>', [
'location' => 'EU',
'cors' => $cors,
]);
// Updating a bucket
$storage->bucket('<bucket-name>')->update([
'cors' => $cors,
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With