PHP Amazon S3 access private files through URL

后端 未结 3 1344
走了就别回头了
走了就别回头了 2021-01-26 09:13

I\'m using AWS PHP sdk to save images on S3. Files are saved privately. Then, I\'m showing the image thumbnails using the S3 file url in my web application but

相关标签:
3条回答
  • 2021-01-26 09:36

    You will need to access the files through a script on your server. That script will do some kind of authentication to make sure the request is valid and you want them to see the file. Then fetch the file from S3 using a valid IAM profile that can access the private files. Output the file

    Instead of requesting the file from S3 request it from http://www.yourdomain.com/fetchimages.php?key=8498439834

    Then here is some pseudocode in 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
    
    ?>
    
    0 讨论(0)
  • 2021-01-26 09:37

    I'd highly advise against this, but you could create a script on your own server that pulls the image via the API, caches it and serves. You can then restrict access however you like without making the images public.

    Example pass through script:

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

    This will barely "touch the sides" and shouldn't delay the appearance of your files too much, but t's still going to take some resources and bandwidth.

    0 讨论(0)
  • 2021-01-26 09:55

    as far as i know you could try to make your S3 bucket a "web server" like this but then you would probably "Make the files public".Then if you have some kind of logic to restrict the access you could create a bucket policy

    0 讨论(0)
提交回复
热议问题