Creating S3 URLs that expire using PHP

After reading this post on the S3 forum I realized that other people are thinking about doing some of the same stuff I have. paolonew was looking for a way to for a way to create URLs to S3 objects that expired. I did this a while back when I was thinking about how to host objects that I wanted to protect with some outside scheme. The confusion on the forum seemed to be about the timestamps used to expire the URL. For PHP it is fairly easy.

To clear up the expiration time issue I think these two steps are needed:

1) Keep in mind that the HTTP header dates must be in GMT.
2) The PHP function time() returns the seconds since the epoch January 1 1970 00:00:00 GMT). Notice here this is in GMT as well.
3) The HTTP Date header you see in a response from an S3 server is the time on that server. The machine you use to sign your request should be synced with that time. I think a good guess is that all the Amazon servers are synced with the atomic clock.

There isn’t much to securing a URL after you have that tucked away. Here is an example that will sign a URL so that it is valid for 60 seconds:

[code lang=”php”]


The hex2b64 function was pulled from the amazon S3 PHP example library.

[tags]amazon s3, s3, php[/tags]

3 thoughts on “Creating S3 URLs that expire using PHP

  1. Robbie

    Developers who copy / paste this and try to use it as is won’t work. You need to replace the &’s with actual &, < with <. And FWIW, Crypt/HMAC.php is a PEAR module. You can install both from the command line without downloading anything.

  2. col000r

    Thanks a lot! Also don’t forget to revoke the open/download permission for “Everyone” in the S3 management console or people will simply be able to delete everything after the filename and download anyway…

  3. Pingback: Direct Browser Uploading – Amazon S3, CORS, FileAPI, XHR2 and Signed PUTs

Comments are closed.