You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP设置Google Cloud Storage对象Cache-Control TTL时元数据错误问题

问题

为优化图片缓存,我需要给Google Cloud Storage(GCS)中的图片设置1年的TTL(默认1小时)。通过命令行可正确设置:

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

但使用PHP代码设置时,Cache-Control被存入自定义元数据而非GCS生效的主元数据,无法用于文件分发(命令行设置会填入GCS控制台中灰色的主Cache-Control栏):

$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)]]);

补充说明:

  • 该问题可能与谷歌官方问题追踪中的同类问题一致;
  • 曾参考Stack Overflow旧问题,但现有解决方案无效。
解决方案

问题根源是代码将Cache-Control嵌套在了metadata子数组中,而GCS的主元数据Cache-Control是顶级属性,无需嵌套。修正后的代码有两种实现方式:

方式一:上传时直接设置

调用upload方法时,直接在配置数组中指定cacheControl参数:

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

方式二:上传后更新

若需在上传后修改,调用update方法时将cacheControl作为顶级属性传入:

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

设置完成后,Cache-Control会被存入GCS的主元数据栏,可正常用于文件分发的缓存策略。

内容的提问来源于stack exchange,提问作者xgretsch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 18:07:28