How To PHP AWS SDK S3 Upload Script

By | December 26, 2018

In this article I show you how to create an Amazon Web Services (AWS) Simple Storage Service (S3) script using the AWS PHP software developer’s kit (SDK). You can create a backup script based on this script to backup and protect your website.

70% of small businesses that have a major data loss go out of business within 6 months. That is why it is so important to learn how to use AWS S3 as a backup tool.

After learning the basics you will be able to extend this script and make a website backup script. You will want, at a bare minimum to backup the content and data of your website. I recommend daily backups that are automated with the Linux cron utility. I will leave extending the script to you.

I used the AWS SDK version 3 for PHP. I created this script on a Linux server running Ubuntu 16.04lts with PHP 7.0.x. installed.

I assume you have command line access to your hosting account.

Steps

  1. Sign up for an AWS Account.
  2. Create Your AWS S3 Credentials
  3. Create a Bucket in S3
  4. Download the PHP SDK With wget
  5. Create a File Named “stuff.txt”
  6. Copy My Script to Your Server
  7. Change The Following Values to Your Information.
    1. $version
    2. $region
    3. $bucket
    4. $credential_key
    5. $credential_secret
    6. $path
    7. $file
  8. Run the Script From The Command Line
  9. Verify the File Named “stuff.txt” is Stored in Your Bucket
  10. Enhance My Script to Meet Your Needs

Sign up for an AWS Account

To create an account, go to the S3 service page.

Then click the “Get started with Amazon S3” button.

Create your account.

Create Your AWS S3 Credentials

  • Go to the AWS Management Console.
  • In the upper right corner click your name.
  • Select “My Security Credentials”.
  • Click “Access keys (access key ID and secret access key)”.
  • Click “Create New Access Key”.
  • Take note of your two keys, AWS access key id and AWS secret access key

Create a Bucket in S3

Download the PHP SDK With the Linux wget Utility and Unzip

To make it easy, lets download the zip file using the Linux wget utility.

This is how I “get” files with wget:

  1. Change to the directory where you want to to download the file.
  2. Visit the page that contains the download link for the SDK in zip format. In this case the page is here
  3. Search this page’s source for the string “download the .zip file”. Then grab the link “https://docs.aws.amazon.com/aws-sdk-php/v3/download/aws.zip”
  4. Simply add “wget” to the download URL like this : wget https://docs.aws.amazon.com/aws-sdk-php/v3/download/aws.zip . Use this on the command line and the file will be downloaded to the directory you are working in.
  5. In the working directory you should find a file named “aws.zip”. Unzip it with the Linux command “unzip aws.zip”

Create a File Named “stuff.txt”

This is self explanatory. Simply create a file names “stuff.txt” in your working directory. You can add some text to the file if you like. This is a test file that will be uploaded to your S3 bucket if successful.

Copy My Script to Your Server

See my script below.

Change The Following Values to Your Information

$version – You can leave it as set. It is set to “latest”.

$region – This information can be found in S3. It is the region of your bucket. Complete list of regions.

$bucket – This is the name of the bucket you created.

$credential_key – This is the credential key you created earlier.

$credential_secret – This is the credential secret you created earlier.

$path – The complete path from the root of the server to include the directory where your backup file located (stuff.txt).

$file – This is the name of the file you created.

Hard Coding Your Credential into the Script

Hard coding your AWS credentials is not the preferred method and is not secure. Ways to secure your credentials 

Run the Script From The Command Line

My file is named basicS3Backup.php. To run it from the Linux command line enter the command “php basicS3Backup.php” and press enter.

Verify the File Named “stuff.txt” is Stored in Your Bucket

After running the script you should see a file in your bucket. If you named your file “stuff.txt”, you will see that file in your bucket.

Enhance My Script to Meet Your Needs

As you can see this is just a basic script that uploads a simple file. To extend this into a website backup script you may want to add the following features:

  • Tar and compress your website’s content
  • Tar and compress your website’s data
  • Name each file using the date, something like YYYY_MM_DD_content and YYYY_MM_DD_data
  • Remove from S3 any files that are older than you want to keep.
  • Send an email to the backup administrator with the status of the backup once the script completes.

You may want other features, these are just some of the features I like.

The AWS S3 PHP Code


#!/usr/bin/php -q
<?php

/*--------------------------------------------------------------------*/
/*   Created by Keith Smith  :  PHPCoderUSA.com                       */
/*   Copyright Keith Smith December 12th 2018                         */
/*                                                                    */
/*   This is a simple AWS S3 file upload script.                      */
/*                                                                    */
/*   Directions can be found at  :                                    */
/*   https://www.phpcoderusa.com/how-to-php-aws-sdk-s3-upload-script  */
/*                                                                    */
/*   You are free to use this script or modify it to your liking.     */
/*   By using this script you acknowledge you will hold               */
/*   Keith Smith Internet Marketing LLC harmless for any ill effects  */
/*   from uing this script.  Also you acknowledge this script is not  */
/*   secure and requires additional work to make it viable for        */
/*   any purpose.                                                     */
/*                                                                    */
/*--------------------------------------------------------------------*/

/* --------------------------------------------  */
/* - - -   Start Configuration Section    - - -  */
/* --------------------------------------------  */

$version                = 'latest';         // Probably set to "latest"
$region                 = '<your-region>';  // See  :  https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html
$bucket                 = '<bucket-name>';  // Name of the bucket

$credential_key         = '<credential-key>';
$credential_secret      = '<credential-secret>';

$path                   = '<path-from-root>';   // Full server path
$file                   = 'stuff.txt';

/* -------------------------------------------- */
/* - - - - -   End of Config Section  - - - - - */
/* -------------------------------------------- */

require 'aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// Hard-coded credentials
try{
        $s3Client = new S3Client([
                'version'     => "$version",
                'region'      => "$region",
                'credentials' => [
                        'key'    => "$credential_key",
                        'secret' => "$credential_secret",
                ],
        ]);
} catch (S3Exception $e) {
        echo $e->getMessage();

}

/*------------------------------*/
/* function upload_file         */
/*------------------------------*/

function upload_file($bucket,$path,$file){
        global $s3Client;
        $path_filename = $path.$file;
        try{
                $result = $s3Client->putObject([
                                'Bucket'     => $bucket,
                                'Key'        => $file,
                                'SourceFile' => $path_filename,
                ]);
        } catch (S3Exception $e) {
                echo $e->getMessage() . "\n";
        }
}

/*------------------------------*/
/* upload file to S3            */
/*------------------------------*/

upload_file($bucket,$path,$file);

/*------------------------------*/
/*          E O F               */
/*------------------------------*/

Conclusion

We know backing up data is important and AWS S3 is one solution to consider. The script I provide is just an example used for learning and is not secure. I offer several features you may want to add to make this script a viable backup script.

You are free to use and modify this script for your use. If you use this script please keep in mind that by using this script you acknowledge you will hold Keith Smith Internet Marketing LLC harmless for any ill effects from using this script. Also you acknowledge this script is not secure and requires additional work to make it viable for any purpose.