【问题标题】:Google Cloud Storage cache management with PHP使用 PHP 管理 Google Cloud Storage 缓存
【发布时间】:2020-12-18 18:46:09
【问题描述】:

我有一个PHP文件可以将图片上传到谷歌云存储,但是每次用户更改他们的个人资料图片时,它都会长时间显示之前的图片,所以他们认为图片根本没有更新。我想知道避免这个问题需要什么缓存和元数据配置。

我不希望使用“自定义元数据”,因为云文档 https://cloud.google.com/storage/docs/metadata 上的这条消息 ->“请注意,使用自定义元数据会产生存储和网络成本。”

这是我的代码:

require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient; 
$storage = new StorageClient([
    'keyFilePath' => $keypath
]);
$storage->registerStreamWrapper();
$bucket = $storage->bucket($url);

$filename    = $_FILES['profile_picture']['name'];
$newFileName = $_POST['user_id'].'_profile.jpg';
$bucket->upload(
    fopen($_FILES["profile_picture"]["tmp_name"], 'r'),
    [
       'name' => $dir.$newFileName,
       'metadata' => [
          'cacheControl' => 'Cache-Control: no-cache, max-age=0',
        ]
    ]
);

我不知道 CacheControl 是否足够(以及 sintax 是否正确)或者我需要包含 Custom-Time 以及它的 sintax 是什么。

我的尝试:

$bucket->upload(
    fopen($_FILES["profile_picture"]["tmp_name"], 'r'),
    [
       'name' => $dir.$newFileName,
       'metadata' => [
          'cacheControl' => 'Cache-Control: no-cache, max-age=0',
          'Custom-Time' => date('Y-m-d\TH:i:s.00\Z');
        ]
    ]
);

文档中没有任何关于 PHP 语法的内容:https://cloud.google.com/storage/docs/metadata

请帮忙

【问题讨论】:

    标签: php caching syntax google-cloud-storage


    【解决方案1】:

    我相信你应该使用:

    $bucket->upload(
        fopen($_FILES["profile_picture"]["tmp_name"], 'r'),
        [
           'name' => $dir.$newFileName,
           'metadata' => [
              'cacheControl' => 'no-cache, max-age=0',
            ]
        ]
    );
    

    我注意到您在代码中重复了 cacheControl。另外,请记住:

    如果您允许缓存,下载可能会继续接收旧版本 对象,即使在上传较新版本之后。这是因为 旧版本在缓存中保持“新鲜”一段时间 由 max-age 决定。此外,因为对象可以缓存在 网上各个地方,没有办法强制缓存 对象全局过期。如果你想阻止服务缓存 公共可读对象的版本,设置 Cache-Control:no-cache, 对象上的 max-age=0。

    如需进一步阅读,请参阅此documentation

    【讨论】:

    • 感谢您修复我的语法,现在可以正常使用了!
    【解决方案2】:

    我的解决方案具有正确的元数据语法:

    $bucket->upload(
       fopen($_FILES["profile_picture"]["tmp_name"], 'r'),
       [
            'name' => $_SESSION['idcompany'].'/uploads/'.$newFileName,
            'metadata' => [
                 'cacheControl' => 'no-cache, max-age=0',
                 'customTime' => gmdate('Y-m-d\TH:i:s.00\Z')
            ]
       ]
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      相关资源
      最近更新 更多