Search code examples
phpgoogle-cloud-storage

Setting Cache-Control TTL from PHP on a Google Cloud Storage object changes the wrong metadata


As recommended by Lighthouse, I am trying to set my images in Google Cloud Storage to a long TTL (the default is 1 hour, I'm trying to set one year). I can set it correctly from the command line, using something like this:

gsutil setmeta -h "Cache-Control:public,max-age=31536000" gs://mybucket/myfolder/myfname.jpg

But what I need to do is to set it using PHP, which I'm doing using Google's recommended code looking like this:

$client = new Google\Cloud\Storage\StorageClient([
   'projectId' => "xxx",
   'keyFilePath' => "yyy.json",
        ]);
$bucket = $client->bucket($bucketname);
$object = $bucket->upload($data, ['name' => "$folder/$objectname"]);
$object->update(['metadata' => ['Cache-Control' => 'public,max-age=' . (3600 * 24 * 365)]]);

The trouble is that the data I provide goes not into the main Cache-Control metadata item, but into a separate "Custom metadata" item, which is not actually used by GCS when serving my file and is therefore useless.

The attached screenshot shows the effect on the metadata. Btw when done using the command line, it's the higher Cache-Control box (in grey on the screenshot) that gets filled in, which is the one that GCS uses when serving the file.

Any ideas on how to make the PHP work?

A couple of notes:

  1. I think this may be the same issue as this one: https://issuetracker.google.com/issues/721233
  2. This question is similar to an old one here, but it's not identical and the answers there didn't work for me: Set Cache-Control on Google Cloud Storage bucket

Metadata shown on console after update.


Solution

  • After help from a Google Cloud partner, it would appear that although you can't update the cache control after upload, you can set it at the time you upload the file. So the following code works (note also the use of cacheControl rather than Cache-Control):

    $client = new Google\Cloud\Storage\StorageClient([
       'projectId' => "xxx",
       'keyFilePath' => "yyy.json",
            ]);
    $bucket = $client->bucket($bucketname);
    $object = $bucket->upload($data, [
       'name' => "$folder/$objectname",
       'metadata' => ['cacheControl' => 'public,max-age=' . (3600 * 24 * 365)]
    ]);