首页 文章

PHP Amazon S3通过URL访问私有文件

提问于
浏览
0

我正在使用 AWS PHP sdk在S3上保存图像 . 文件以私密方式保存 . 然后,我在我的Web应用程序中使用S3文件URL显示图像缩略图,但由于文件是私有的,因此图像显示为损坏 .

enter image description here

当用户单击文件名时,会打开一个模式以显示更大的文件,但由于同样的问题,文件也会显示为损坏 .

enter image description here

现在,我知道有两种方法可以实现这一目标 . 1. Make the files public. 2. Generate pre-signed urls for files. 但由于我的项目要求,我无法使用这两个选项中的任何一个 .

我的问题是,有没有第三种方法可以解决这个问题?

3 回答

  • 0

    我强烈反对这一点,但您可以在自己的服务器上创建一个脚本,通过API提取图像,缓存并提供服务 . 然后,您可以根据需要限制访问,而无需公开图像 .

    示例传递脚本:

    $headers = get_headers($realpath); // Real path being where ever the file really is
    
    foreach($headers as $header) {
        header($header);
    }
    $filename = $version->getFilename();
    
    // These lines if it's a download you want to do
    // header('Content-Description: File Transfer');
    // header("Content-Disposition: attachment; filename={$filename}");
    
    $file = fopen($realpath, 'r');
    fpassthru($file);
    fclose($file);
    exit;
    

    这几乎不会“触及两侧”,不应该过多地延迟文件的出现,但仍然会占用一些资源和带宽 .

  • 1

    您需要通过服务器上的脚本访问这些文件 . 该脚本将执行某种身份验证以确保请求有效并且您希望它们查看该文件 . 然后使用可以访问私有文件的有效IAM配置文件从S3获取文件 . 输出文件

    而不是从S3请求文件请求它来自http://www.yourdomain.com/fetchimages.php?key=8498439834

    然后这里是fetchimages.php中的一些伪代码

    <?php
    
    //if authorized to get this image
    
    $key=$_GET['key'];
    //validate key is the proper format
    
    //get s3 url from a database based on the $key
    
    //connect to s3 securely and read the file from s3
    
    //output the file
    
    ?>
    
  • 2

    据我所知,你可以尝试让你的S3存储桶"web server" like this然后你可能会"Make the files public" . 然后,如果你有某种逻辑来限制访问,你可以创建一个bucket policy

相关问题