Last Updated: February 25, 2016
·
3.425K
· felipebrnd

Create AWS S3 Signed Requests with PHP

Here is a simple way to generate a signed request for objects at Amazon S3:

//request variables:
$awsKeyId = AWS_KEY_ID;                       
$awsSecret = AWS_SECRET;                      
$expires = time() + (5*60);                   
$httpVerb = "GET";
$contentMD5 = "";
$contentType = "";
$amzHeaders = "";
$amzResource = "/BUCKETNAME/" . $filename;

//request to be signed:
$request = sprintf("%s\n%s\n%s\n%s\n%s%s" , $httpVerb , $contentMD5 , $contentType , $expires , $amzHeaders , $amzResource );

//signing:
$base64signed = base64_encode( hash_hmac( 'sha1' , $request, $awsSecret , true ) );

//the final url:
$url = "http://s3.amazonaws.com%s?AWSAccessKeyId=%s&Expires=%s&Signature=%s";
$url = sprintf( $url , $amzResource , $awsKeyId , $expires , $base64signed );

The final link will be available only for 5 minutes, look at $expires.

The $httpVerb can be switched to HEAD if you just want to check if the key exist.

This code is based on a a python example I found other day.

2 Responses
Add your response

We have about 10+ images on a page and every page load about 2-3 will not show.
Have you seen this before?

Thanks

over 1 year ago ·

Hey, try checking if your $expire parameter is not too small (like a few milliseconds).

over 1 year ago ·