Skip to main content

Uploading files to Amazon S3 using PHP

At KnackForge we offer hosting services to most of the sites and applications we develop. Being a small team we try to automate most of our processes, and here is an attempt to make it for backup, archive and upload to Amazon Simple Storage Service (S3).

If you are reading this post you are probably more aware of the essence of backup. This post starts with a bit of introduction to S3 and goes along with a simple case script together with brief explanation.


Nobody can say better than Amazon. Here is what they say about one of their services,
Amazon S3 is storage for the Internet. It is designed to make web-scale computing easier for developers.
Amazon S3 provides a simple web services interface that can be used to store and retrieve any amount of data, at any time, from anywhere on the web. It gives any developer access to the same highly scalable, reliable, secure, fast, inexpensive infrastructure that Amazon uses to run its own global network of web sites. The service aims to maximize benefits of scale and to pass those benefits on to developers.
There is a nice  PHP SDK to access Amazon API. I am going to write about uploading files to S3. Download the latest SDK from Amazon website,


In the file within the SDK, fill the following values,
  1. AWS Key: Found in the AWS Security Credentials. Click on My Account -> Security Credentials.
  2. AWS_SECRET_KEY: Found in the AWS Security Credentials.
  3. AWS_CANONICAL_ID: Found in the AWS Security Credentials.
  4. AWS_CANONICAL_NAME: Your welcome name, i.e. "Welcome, AWS_CANONICAL_NAME"
Leave the rest for the case of S3.


  1. <?php
  2. $bucket_name 'Test';
  3. require_once('sdk_VERSION/sdk.class.php');//use appropriate version
  4. $s3 = new AmazonS3();
  5. /*Check if the same bucket has already been created*/
  6. if (!$s3->if_bucket_exists($bucket_name){
  7.     $response = $s3->create_bucket($bucket_name, AmazonS3::REGION_US_E1, AmazonS3::ACL_PUBLIC);
  8. }
  9. if ($argc != 2{
  10.     exit("Usage: " . $argv[0] . " object name \n");
  11. }
  12. $object = $argv[1];
  13. /*Store the specified object into the bucket */
  14. $response = $s3->create_object($bucket_name, $objectarray('fileUpload'=>$object));
  15. echo $response->isOK();
  16. print_r($response);
  17. ?>
Let us call this script as s3backup.php.

How to run:

$ php s3backup.php SOME_FILE.tar.gz
The above code creates a new bucket called Test, if it does not already exist. Then sends the sample file SOME_FILE.tar.gz to S3 storage.
You can visit the amazon console and set the lifetime for your objects in days. Those object will be automatically deleted by Amazon, though there will be a little lag.


AJMAL (not verified)

Sat, 08/13/2016 - 00:53

PLease Help Me
How do I supposed to upload a dynamically generated (mpdf file ) to aws s3 server????????