As we all know, Amazon S3 is a cost-effective, reliable, fast and secure object storage system, which allows us to store and retrieve any amount of data from anywhere on the web. Today I am going to show you how you can directly upload any file to Amazon AWS S3 using HTML Form and PHP without compromising your own server security and upload latency.
Create User and Bucket
- First step is to create a bucket by visiting AWS S3 Console, this is where we will be uploading files. Note down its name and AWS region.
- Create a IAM user profile by going in your AWS Management Console, after user creation you should be presented with unique Access Key ID and Secret Access Key, you should write them down as we will need them in our PHP code.
- Now create a new Policy for user in Create Policy Console (Or Copy-paste Policy Document below) and attach the Policy to IAM user you’ve just created.
You can also create IAM policy quickly using policy generator.
- Now create another “S3 Bucket policy” for your bucket using policy generator. go back to the bucket you’ve created, click its properties, scroll down to permissions tab and click edit bucket policy, now copy/paste policy text you’ve just created. Eg:
Once everything is set correctly in AWS console, we can now create an HTML form that can upload content to Amazon S3 directly.
As you can see, there are some pre-filled texts in our form, which need to be replaced with specific values, such as Signature field (X-Amz-Signature) it requires a SHA256 calculated signature, and Policy field requires Base64-encoded policy string. We need to generate these values using PHP in the next section.
Creating POST Policy and Calculating Signature using PHP
In our PHP code we need previously created user Access Key, Secret Key and several other values such as bucket name and region, using these variables wen can construct a POST policy and calculate AWS Signature (Version 4) which are required in our HTML upload form.
Policy is Base64 encoded security policy that describes what is permitted in the request. For authenticated requests a policy is required, you can learn more about constructing HTTP POST Policy here.
Signature is the HMAC-SHA256 hash of the security policy using AWS Signature Version 4, and is required if a policy document is included with the request, more about AWS Signature Version 4 here.
After successful upload, AWS redirects user to success page specified in success_action_redirect form field and policy document, it also attaches bucket, etag and key in the query string, which we can use to quickly generate a link to uploaded object on our S3 bucket.
Putting It All Together
All we got to do now is put them together in a single PHP file.
That’s it! you can copy this code or download and play with your own Aws S3 credentials . You can also check-out the demo page that directly uploads files in my S3 bucket, Good luck!