Getting Started with AWS SDK for PHP

Amazon Web Services (AWS) is the most popular cloud platform and is used by companies all over the globe for their infrastructure needs.   The service offers a full featured SDK which allows you to develop solutions that cater to your needs.

Installation

You can use Composer to install the SDK from a Linux command-line

composer require aws/aws-sdk-php
Using version ^3.16 for aws/aws-sdk-php
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing mtdowling/jmespath.php (2.3.0)
    Downloading: 100%

  - Installing guzzlehttp/promises (1.1.0)
    Downloading: 100%

  - Installing psr/http-message (1.0)
    Downloading: 100%

  - Installing guzzlehttp/psr7 (1.2.3)
    Downloading: 100%

  - Installing guzzlehttp/guzzle (6.1.1)
    Downloading: 100%

  - Installing aws/aws-sdk-php (3.16.0)
    Downloading: 100%

Writing lock file
Generating autoload files

Usage

The basic idea is that you create a client object for each service you want to talk to (EC2, Route53, S3, etc).  Each client implements its own methods and returns an object containing results which you can parse. 

In order to create the client object, you need to pass a configuration array into the constructor of the AWS\Sdk class.   This is new in v3 and serves as a factory for creating clients for different types of services.  

require 'vendor/autoload.php';

// Configuration parameters
$config = [
    'region'  => 'us-east-1',
    'version' => 'latest',
        'credentials' => [
        'key'    => 'XXXX',
        'secret' => 'XXXX',
    ],
];

// SDK object 
$sdk = new Aws\Sdk($config);

// S3 Client 
$s3 = $sdk->createS3();
$result = $s3->listBuckets();
var_dump($result['Buckets']);

// EC2 Client
$ec2 = $sdk->createEC2();
$reservations = $ec2->describeInstances();

// Get instance information
foreach ($reservations as $r)
{
     $instances = $r['Instances'];
     
     // Iterate through instances
     foreach ($instances as $i)
     {
        var_dump($i);
     }
}