Skip to content

Instantly share code, notes, and snippets.

@masazdream
Created January 31, 2013 13:47
Show Gist options
  • Save masazdream/4682985 to your computer and use it in GitHub Desktop.
Save masazdream/4682985 to your computer and use it in GitHub Desktop.
<?php
class FileReadURL{
function getUrl(){
$aws_access_key_id = '[読み取り用のAWSキー]';
$aws_secret_key = '[読み取り用のAWSシークレットキー]';
$aws_bucket = 'バケット名';
$downloadAudioTimeout = '作成したURLの有効時間';
$file_path = '[ディレクトリパス]/[ファイル名]';
$http_verb = "GET";
$content_md5 = "";
$content_type = "";
$expires = strtotime($downloadAudioTimeout);
$canonicalizedAmzHeaders = "";
$canonicalizedResource = '/' . $aws_bucket . '/' . $file_path;
$stringToSign = $http_verb . "\n" . $content_md5 . "\n" . $content_type . "\n" . $expires . "\n" . $canonicalizedAmzHeaders . $canonicalizedResource;
$signature = urlencode($this->hex2b64($this->hmacsha1($aws_secret_key, utf8_encode($stringToSign))));
$url = "https://$aws_bucket.s3.amazonaws.com/$file_path?AWSAccessKeyId=$aws_access_key_id&Signature=$signature&Expires=$expires";
return $url;
}
private function hmacsha1($key,$data)
{
$blocksize=64;
$hashfunc='sha1';
if (strlen($key)>$blocksize)
$key=pack('H*', $hashfunc($key));
$key=str_pad($key,$blocksize,chr(0x00));
$ipad=str_repeat(chr(0x36),$blocksize);
$opad=str_repeat(chr(0x5c),$blocksize);
$hmac = pack(
'H*',$hashfunc(
($key^$opad).pack(
'H*',$hashfunc(
($key^$ipad).$data
)
)
)
);
return bin2hex($hmac);
}
/*
* Used to encode a field for Amazon Auth
* (taken from the Amazon S3 PHP example library)
*/
private function hex2b64($str)
{
$raw = '';
for ($i=0; $i < strlen($str); $i+=2)
{
$raw .= chr(hexdec(substr($str, $i, 2)));
}
return base64_encode($raw);
}
}
$obj = new FileReadURL();
echo $obj->getUrl();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment