5
votes

I have a bucket with public images that are frequently updated and would like to disable the default cache duration of 3600. (E.g. "Cache-Control:private, max-age=0, no-transform")

Can the Cache-Control be set on a file while uploading it with PHP?

Is there a way to set the default Cache-Control for all future files in the bucket (like with ACL that all files are public)?

Right now I can only set it Cache-Control with gsutil and only for files currently on storage.

2
While not documented, you can set Cache-Control via stream context, the same as you do with Content-Type (developers.google.com/appengine/docs/php/googlestorage/…). - Mars
@Mars I'm sorry but I cannot get this to work with Cache-Control (however it does work with Content-Type as you wrote). It would have been a great solution. - Max Nilsson
Could you please file a feature request at code.google.com/p/googleappengine/issues/list?q=Language%3DPHP thanks. - Mars

2 Answers

3
votes

You can set the Cache-Control while uploading an object - I suggest you use gsutil -D to see an example of the request it generates to do this, and then translate that to PHP:

gsutil -D -h Cache-Control:"Cache-Control:private, max-age=0, no-transform" \
    cp file gs://your-bucket/file

There's no way to set a default Cache-Control for the bucket.

2
votes

Here is an example I created after finding your question. In the below I want the file I upload to not be cached:

$this->bucket->upload(
  $content,
  [
    'name' => $name,
    'metadata' => [
      'cacheControl' => "public, max-age=0"
    ]
  ]
);

I worked this out by:

  1. Going to the repo: https://github.com/googleapis/google-cloud-php-storage
  2. That lead to the official docs: https://cloud.google.com/storage/docs
  3. I found the PHP reference: https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.122.0/storage/storageclient
  4. Which contained the bucket's upload reference: https://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.122.0/storage/bucket?method=upload
  5. Which recommends using the JSON API reference for metadata https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request-body
  6. Which links to a rfc spec doc for cache control https://tools.ietf.org/html/rfc7234#section-5.2

All of the above were useful resources, but hopefully my answer will be more succinct for future "Googlers".