PHP Amazon S3 File Upload Code AWS Signature Version 4

Amazon offers a PHP SDK for taking care of AWS and S3 asks for, yet it tips the scales at more than 500 documents and almost 5MB. In the event that you simply need to transfer a record to a S3 basin utilizing PHP, you can make the HTTP POST ask for yourself utilizing just around 50 lines of code. This is likewise helpful on the off chance that you need to see how the demand and approval prepare function.

AWS Signature Version 4
This code uses Amazon AWS Signature Version 4. To view the old Version 2 code, see this post.

Sample Code
This is test PHP code to help you comprehend and test transferring to Amazon S3. Requires PHP variant 5.4 or fresher because of exhibit language structure. On the off chance that you need to utilize this in your venture, you ought to most likely alter this and place it into a capacity or strategy. I have it designed like this particularly to help demonstrate how the procedure functions.

Perused the inline code remarks for a clarification of each segment:


// Replace these values with ones appropriate to you.
$accessKeyId = 'YOUR_ACCESS_KEY_ID';
$secretKey = 'YOUR_SECRET_KEY';
$bucket = 'YOUR_BUCKET_NAME';
$region = 'BUCKET_AMAZON_REGION'; // us-west-2, us-east-1, etc
$acl = 'ACCESS_CONTROL_LIST'; // private, public-read, etc
$filePath = 'path/to/file.jpg';
$fileName = 'myimage.jpg';
$fileType = 'image/jpeg';

// These are used throughout the request.
$longDate = gmdate('Ymd\THis\Z');
$shortDate = gmdate('Ymd');
$credential = $accessKeyId . '/' . $shortDate . '/' . $region . '/s3/aws4_request';

// Amazon requires a base64-encoded POST policy written in JSON.
// This tells Amazon what is acceptable for this request. For
// simplicity, we set the expiration date to always be 24H in 
// the future. The two "starts-with" fields are used to restrict
// the content of "key" and "Content-Type", which are specified
// later in the POST fields. Again for simplicity, we use blank
// values ('') to not put any restrictions on those two fields.
$policy = base64_encode(json_encode([
    'expiration' => gmdate('Y-m-d\TH:i:s\Z', time() + 86400),
    'conditions' => [
        ['acl' => $acl],
        ['bucket' => $bucket],
        ['starts-with', '$Content-Type', ''],
        ['starts-with', '$key', ''],
        ['x-amz-algorithm' => 'AWS4-HMAC-SHA256'],
        ['x-amz-credential' => $credential],
        ['x-amz-date' => $longDate]

// A base64-encoded HMAC hashed signature with your secret key.
// This is used so Amazon can verify your request, and will be
// passed along in a POST field later.
$signingKey = hash_hmac('sha256', $shortDate, 'AWS4' . $secretKey, true);
$signingKey = hash_hmac('sha256', $region, $signingKey, true);
$signingKey = hash_hmac('sha256', 's3', $signingKey, true);
$signingKey = hash_hmac('sha256', 'aws4_request', $signingKey, true);
$signature = hash_hmac('sha256', $policy, $signingKey);

// The cURL request. Passes in the full URL to your Amazon bucket.
// Sets RETURNTRANSFER and HEADER to true to see the full response from
// Amazon, including body and head. Sets POST fields for cURL.
// Then executes the cURL request.
$ch = curl_init('https://' . $bucket . '.s3-' . $region . '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'Content-Type' =>  $fileType,
    'acl' => $acl,
    'key' => $fileName,
    'policy' =>  $policy,
    'x-amz-algorithm' => 'AWS4-HMAC-SHA256',
    'x-amz-credential' => $credential,
    'x-amz-date' => $longDate,
    'x-amz-signature' => $signature,
    'file' => new CurlFile(realpath($filePath), $fileType, $fileName)
$response = curl_exec($ch);

// If Amazon returns a response code of 204, the request was
// successful and the file should be sitting in your Amazon S3
// bucket. If a code other than 204 is returned, there will be an
// XML-formatted error code in the body. For simplicity, we use
// substr to extract the error code and output it.
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == 204) {
    echo 'Success!';
} else {
    $error = substr($response, strpos($response, '<code>') + 6);
    echo substr($error, 0, strpos($error, '</code>'));
If you aren't receiving any response at all, check if curl_exec($ch) is returning false. If it is, chances are it's due to an SSL issue. You can check the error at curl_error($ch). For testing purposes, you can set these two additional cURL options and see if it works:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
But note that doing this is very insecure. Read this Stackoverflow post and this blog post.


Post a Comment