AWS S3 Tutorial: a quick PHP SDK introduction

Beginning by this episode we will be trying to examine all the possibilities offered to us by the various AWS SDKs. This time is the turn of PHP‘s SDK, we will explore all the others in times to come.

This tutorial’s code is trivial, you wouldn’t put it into production, it has nothing to do with a modular and OOP style of programming. In spite of its simplicity, it can give you all the key concepts that can guide you through the learning of AWS SDKs.

The Php programming language

The first thing I wanna do is to give you some references to start your learning, you will find some interesting stuff in this introduction page of AWS SDK for PHP.

But now comes the time to get our hands dirty, let’s begin by creating a working directory and installing our SDK through Composer:

$ mkdir s3_php_tutorial
$ composer require aws/aws-sdk-php

The second thing is to create a bootstrap file called get_client.php, which just loads our dependencies by means of Composer, loads an ini file with our credentials and creates an S3 client object:

<?php
     
     require './vendor/autoload.php';
     
     use Aws\S3\S3Client;
     use Aws\Credentials\CredentialProvider;
     use Aws\S3\Exception\S3Exception;
     
     $profile = 'default';
     $path = './credentials.ini';
     
     $provider = CredentialProvider::ini($profile, $path);
     $provider = CredentialProvider::memoize($provider);
     
     $s3Client = new S3Client([
         'region'      => 'eu-central-1',
         'version'     => 'latest',
         'credentials' => $provider
     ]);

Here is our credentials.ini file, remember to put your own credentials:

[default]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY

The second thing you should do, is to create a create_bucket.php file with an HTML form which takes a name for your S3 Bucket and creates it.

Remember that not all characters are allowed in Buckets names, plus if that Bucket’s name is assigned to another AWS user, you can get an error: it must be a unique name.

<?php
     
     if(isset($_POST['bucket_name'])) {
     
         require 'get_client.php';
         
         try {
         
             $s3Client->createBucket([
                 'Bucket' => $_POST['bucket_name'],
             ]);
         
         } catch (Aws\S3\Exception\S3Exception $e) {
         
             echo "Error in creating your Bucket, try again.<br/>";
             echo '<a href="create_bucket.php">Create a new Bucket</a>';
             die();
         
         }
         
         header("Location: show_buckets.php");
         die();
         
     }
     
 ?>
   
 <div align="center">
   <h1>Create a new Bucket:</h1>
   <form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST">
     <input type="text" name="bucket_name"/>
     <input type="submit"/>
   </form>
   <a href="show_buckets.php">Show all of my Buckets</a>
 </div>

Now it’s time to show our newly created Buckets, with the possibility of putting files in it, deleting files, deleting a Bucket. Let’s create a file named show_buckets.php with the following content:

<div align="center">
   <h1>All of my Buckets:</h1>
   
 <?php
     
     require 'get_client.php';
     
     $bucket_list = $s3Client->listBuckets([]);
     
     foreach ($bucket_list['Buckets'] as $bucket) {
     
         $bucket_name = $bucket['Name'];
         
         $objects = $s3Client->listObjects([
             'Bucket' => $bucket_name
         ]);
         
         echo $bucket_name,
         " - <a href='delete_buckets.php?bucket_name=$bucket_name'>Delete</a>",
         " - <a href='put_files.php?bucket_name=$bucket_name'>Put Files</a>",
         "<br/>";
         
         if(isset($objects['Contents'])) {
           foreach ($objects['Contents'] as $object) {
           
             $file_name = $object['Key'];
             
             echo $file_name,
             " - <a href='delete_files.php?bucket_name=$bucket_name&file_name=$file_name'>Delete File</a>",
             "<br/>";
           }
           
         }
         echo "<hr/>";
         
     }
     
 ?>
   
   <a href="create_bucket.php">Create a new Bucket</a>
 </div>

Let’s create our put_files.php, which loads a file from an HTML form and puts it inside the Bucket:

<?php
     
     if(isset($_FILES['file_to_upload'])) {
     
         require 'get_client.php';
         
         $file_name = $_FILES['file_to_upload']['name'];
         $temp_file_location = $_FILES['file_to_upload']['tmp_name'];
         
         $result = $s3Client->putObject([
             'Bucket' => $_POST['bucket_name'],
             'Key'    => $file_name,
             'SourceFile' => $temp_file_location
         ]);
         
         header("Location: show_buckets.php");
         die();
         
     }
     
 ?>
   
 <div align="center">
   <h1>Put a new file into my Bucket:</h1>
   <form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
     <input type="hidden" name="bucket_name" value="<?php echo $_GET['bucket_name']?>"/>

    <input type="file" name="file_to_upload"/>
     <input type="submit"/>
  </form>
   <a href="show_buckets.php">Show all of my Buckets</a>
 </div>

We’re almost done by creating a delete_files.php:

<?php
     
     if(isset($_GET['file_name'])) {
     
         require 'get_client.php';
         
         $s3Client->deleteObject([
             'Bucket' => $_GET['bucket_name'],
             'Key'    => $_GET['file_name'],
         ]);
         
     }
     
     header("Location: show_buckets.php");
     die();


The last touch is creating a PHP file that deletes a Bucket, remember that it will first empty the Bucket, then delete it. It will be called delete_buckets.php:

<?php
     
     if(isset($_GET['bucket_name'])) {
     
         require 'get_client.php';
         
         $objects = $s3Client->listObjects([
             'Bucket' => $_GET['bucket_name']
         ]);
         
         if(isset($objects['Contents'])) {
         
             $delete = array('objects'=>array());
             
             foreach ($objects['Contents'] as $object) {
                 $delete['Objects'][]['Key']
                         = (string)$object['Key'];
             }
             
             $s3Client->deleteObjects([
                 'Bucket' => $_GET['bucket_name'],
                 'Delete' => $delete
             ]);
             
         }
         
         $s3Client->deleteBucket([
             'Bucket' => $_GET['bucket_name'],
         ]);
         
     }
     
     header("Location: show_buckets.php");
     die();

And there’s nothing left to do, run it inside a PHP installation and it should be working. Create a Bucket, upload files and check through your web console that all the operations have gone well.

Should you need more explanations, contact me in person. For the full code of this tutorial go this GitHub repository, after cloning it, run the following command to download all the dependencies:

$ composer install

All right then, we just saw how to create a simple managing application with the help of PHP and its AWS SDK.

In the next episodes we will be talking more about AWS SDKs and there will be surprises, till then, thanks for reading me and see you soon.

Did you like this post? Please comment here below and share it on your preferred social networks, thank you!

2 thoughts on “AWS S3 Tutorial: a quick PHP SDK introduction

  1. Hello,
    from a technical point of view, this tutorial is quite basic.
    It’s interesting but I was thinking of something more advanced and more specific.

    Anna

  2. Thanks Anna,
    for your feedback and for reading my tutorials.
    This blog aims at spreding basic informatics concepts and technologies, otherwise a prerogative of the few.
    But you’re right, something more advenced is needed to complete my teaching.
    And maybe in the near future there’re will be room for a dedicated section for more technical and specific topics.

    And you guys, let me know if it is a good idea
    keep commenting and keep reading this website,
    Thanks

Leave a Reply

Give me your opinion, I will be grateful.