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.
You can also create IAM policy quickly using policy generator.
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.
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.
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!