Skip to content

Instantly share code, notes, and snippets.

@Maxwell2022
Last active July 10, 2016 21:20
Show Gist options
  • Save Maxwell2022/5480701 to your computer and use it in GitHub Desktop.
Save Maxwell2022/5480701 to your computer and use it in GitHub Desktop.
<?php
function getS3Settings($filename)
{
$AWSbucket = 'YOUR_BUCKET_NAME';
$AWSkey = 'YOUR_ACCESS_KEY';
$AWSsecret = 'YOUR_SECRET_KEY';
$acl = 'public-read'; // private
// Get the file extension
$file = pathinfo($filename);
if (!$file) {
return false;
}
// Prepare the filename
$fileName = 'c'.sha1(uniqid(mt_rand(), true));
$key = 'path/to/object/'.$fileName.'.'.$file['extension'];
// Set the expiration time of the policy
$policyExpiration = gmdate('Y-m-d\TH:i:s\Z', strtotime('+24 hour'));
// Set the policy
$policy = str_replace("\n", "", '
{"expiration": "'.$policyExpiration.'",
"conditions": [
{"acl": "'.$acl.'"},
{"bucket": "'.$AWSbucket.'"},
{"success_action_status": "201"},
["starts-with", "$key", "'.$key.'"],
["starts-with", "$Content-Type", "image/"]
]
}');
// 1 - Encode the policy using UTF-8.
// 2 - Encode those UTF-8 bytes using Base64.
// 3 - Sign the policy with your Secret Access Key using HMAC SHA-1.
// 4 - Encode the SHA-1 signature using Base64.
// Prepare the signature
$b64 = base64_encode(utf8_encode($policy));
$signature = base64_encode(hash_hmac('sha1', $b64, $AWSsecret, true));
// Return the post information
return array(
'Content-Type' => $contentType,
'key' => $key,
'acl' => $acl,
'policy' => $b64,
'signature' => $signature,
'AWSAccessKeyId' => $AWSkey,
'success_action_status' => 201,
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment