Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Access-Control-Allow-Origin header to file uploaded using PHP client library

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

like image 491
Jim L Avatar asked Dec 07 '22 20:12

Jim L


2 Answers

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

like image 150
Jim L Avatar answered Jun 23 '23 14:06

Jim L


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,
]);
like image 29
nick Avatar answered Jun 23 '23 14:06

nick