How do I display protected Amazon S3 images on my secure site using PHP? How do I display protected Amazon S3 images on my secure site using PHP? php php

How do I display protected Amazon S3 images on my secure site using PHP?


The best way to serve your images is to generate a url using the PHP SDK. That way the downloads go directly from S3 to your users.

You don't need to download via your servers as @mfonda suggested - you can set any caching headers you like on S3 objects - and if you did you would be losing some major benefits of using S3.

However, as you pointed out in your question, the url will always be changing (actually the querystring) so browsers won't cache the file. The easy work around is simply to always use the same expiry date so that the same querystring is always generated. Or better still 'cache' the url yourself (eg in the database) and reuse it every time.

You'll obviously have to set the expiry time somewhere far into the future, but you can regenerate these urls every so often if you prefer. eg in your database you would store the generated url and the expiry date(you could parse that from the url too). Then either you just use the existing url or, if the expiry date has passed, generate a new one. etc...


You can use bucket policies in your Amazon bucket to allow your application's domain to access the file. In fact, you can even add your local dev domain (ex: mylocaldomain.local) to the access list and you will be able to get your images. Amazon provides sample bucket policies here: http://docs.aws.amazon.com/AmazonS3/latest/dev/AccessPolicyLanguage_UseCases_s3_a.html. This was very helpful to help me serve my images.

The policy below solved the problem that brought me to this SO topic:

    {       "Version":"2008-10-17",       "Id":"http referer policy example",       "Statement":[    {      "Sid":"Allow get requests originated from www.example.com and example.com",      "Effect":"Allow",      "Principal":"*",      "Action":"s3:GetObject",      "Resource":"arn:aws:s3:::examplebucket/*",      "Condition":{        "StringLike":{          "aws:Referer":[            "http://www.example.com/*",            "http://example.com/*"          ]        }      }    }  ]}


When you talk about security and protecting data from unauthorized users, something is clear: you have to check every time you access that resource that you are entitled to.

That means, that generating an url that can be accessed by anyone (might be difficult to obtain, but still...). The only solution is an image proxy. You can do that with a php script.

There is a fine article from Amazon's blog that sugests using readfile, http://blogs.aws.amazon.com/php/post/Tx2C4WJBMSMW68A/Streaming-Amazon-S3-Objects-From-a-Web-Server

readfile('s3://my-bucket/my-images/php.gif');