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:

<?php

require_once('Crypt/HMAC.php');

echo getS3Redirect("/test.jpg") . "\n";

function getS3Redirect($objectName)
{
  $S3_URL = "http://s3.amazonaws.com";
  $keyId = "your key";
  $secretKey = "your secret";
  $expires = time() + 60;
  $bucketName = "/your bucket";

  $stringToSign = "GET\n\n\n$expires\n$bucketName$objectName";
  $hasher =&amp; new Crypt_HMAC($secretKey, "sha1");
  $sig = urlencode(hex2b64($hasher-&gt;hash($stringToSign)));

  return "$S3_URL$bucketName$objectName?AWSAccessKeyId=$keyId&amp;Expires=$expires&amp;Signature=$sig";
}

function hex2b64($str)
{
    $raw = ";
    for ($i=0; $i &lt; strlen($str); $i+=2)
    {
        $raw .= chr(hexdec(substr($str, $i, 2)));
    }
    return base64_encode($raw);
}

?>

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *