Posted By

esundahl on 01/08/11


Tagged

link generator expire s3


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

AllKnightAccess
notturnale


Amazon S3 Expiring Link


 / Published in: PHP
 

This script generates an expiring link to an Amazon S3 file

  1. <?php
  2. // ----------------------------------------------------------------------- //
  3. if(!function_exists('el_crypto_hmacSHA1')){
  4. /**
  5.   * Calculate the HMAC SHA1 hash of a string.
  6.   *
  7.   * @param string $key The key to hash against
  8.   * @param string $data The data to hash
  9.   * @param int $blocksize Optional blocksize
  10.   * @return string HMAC SHA1
  11.   */
  12. function el_crypto_hmacSHA1($key, $data, $blocksize = 64) {
  13. if (strlen($key) > $blocksize) $key = pack('H*', sha1($key));
  14. $key = str_pad($key, $blocksize, chr(0x00));
  15. $ipad = str_repeat(chr(0x36), $blocksize);
  16. $opad = str_repeat(chr(0x5c), $blocksize);
  17. $hmac = pack( 'H*', sha1(
  18. ($key ^ $opad) . pack( 'H*', sha1(
  19. ($key ^ $ipad) . $data
  20. ))
  21. ));
  22. return base64_encode($hmac);
  23. }
  24. }
  25. // ----------------------------------------------------------------------- //
  26. if(!function_exists('el_s3_getTemporaryLink')){
  27. /**
  28.   * Create temporary URLs to your protected Amazon S3 files.
  29.   *
  30.   * @param string $accessKey Your Amazon S3 access key
  31.   * @param string $secretKey Your Amazon S3 secret key
  32.   * @param string $bucket The bucket (bucket.s3.amazonaws.com)
  33.   * @param string $path The target file path
  34.   * @param int $expires In minutes
  35.   * @return string Temporary Amazon S3 URL
  36.   * @see http://awsdocs.s3.amazonaws.com/S3/20060301/s3-dg-20060301.pdf
  37.   */
  38.  
  39. function el_s3_getTemporaryLink($accessKey, $secretKey, $bucket, $path, $expires = 5) {
  40. // Calculate expiry time
  41. $expires = time() + intval(floatval($expires) * 60);
  42. // Fix the path; encode and sanitize
  43. $path = str_replace('%2F', '/', rawurlencode($path = ltrim($path, '/')));
  44. // Path for signature starts with the bucket
  45. $signpath = '/'. $bucket .'/'. $path;
  46. // S3 friendly string to sign
  47. $signsz = implode("\n", $pieces = array('GET', null, null, $expires, $signpath));
  48. // Calculate the hash
  49. $signature = el_crypto_hmacSHA1($secretKey, $signsz);
  50. // Glue the URL ...
  51. $url = sprintf('http://%s.s3.amazonaws.com/%s', $bucket, $path);
  52. // ... to the query string ...
  53. $qs = http_build_query($pieces = array(
  54. 'AWSAccessKeyId' => $accessKey,
  55. 'Expires' => $expires,
  56. 'Signature' => $signature,
  57. ));a
  58. // ... and return the URL!
  59. return $url.'?'.$qs;
  60. }
  61. }

Report this snippet  

You need to login to post a comment.