How to Install AWS SDK for PHP – Complete Guide

How to Install AWS SDK for PHP

The article demonstrates how to install AWS SDK for PHP. If you’re unfamiliar with AWS SDK, it is recommended to read the complete article. Here’s a breakdown of this walkthrough.

  1. Getting Started
  2. Install AWS SDK for PHP
  3. Setup Credentials for Authentication
  4. Basic Usage

Getting Started | AWS SDK for PHP 

AWS Software Development Kit (SDK) is an open-source library for PHP which helps integrate AWS into your PHP applications. You can programmatically access AWS services and resources using AWS SDK.

The article is a walkthrough of installing AWS SDK for PHP Version 3. It is recommended to follow thoroughly.  

Prerequisites

AWS SDK for PHP Version 3 requires.

  • PHP version 5.5.0 or later.
  • SimpleXML PHP extension enabled. (Enabled by default)

Note: Some Linux distributions don’t have the SimpleXML extension enabled by default. Run sudo apt-get install php-xml to get started.

Recommendations

In addition to prerequisites, we suggest you should install the following.

Installation | AWS SDK for PHP

You can install AWS SDK for PHP via these options.

We are using the composer method for this article. If you want to learn more about the phar or zip option, learn more here

This guide will use Composer as it is the standard for PHP package management 

Add AWS SDK for PHP via Composer

If Composer is globally installed, you can run the following command in the base directory of your PHP project.

composer require aws/aws-sdk-php

Otherwise, you can run this command to install it as a dependency.

php -d memory_limit=-1 composer.phar require aws/aws-sdk-php

Your project directory will now include the following files.

  • A vendor folder.
  • composer.json
  • composer.lock

Setting Credentials | AWS PHP SDK

We need to set up our credentials, so the program can access them and pass them on to the SDK for authentication. We can securely set up credentials through role-based access, a credentials file, or a .ENV file. Using AWS role-based access is the most secure and recommended whereas the credentials & env files are recommended if you don’t host your website through AWS.

  1. IAM EC2 Role-Based Access
  2. Environment Files
  3. AWS credential file and credential profile

For authentication, the SDK looks for credentials in the environment file using getenv(), AWS credential files, or credential providers.

There are other ways to set up credentials, but we will use the most convenient ones. Learn more about those here.

Note: Never hardcode AWS credentials in the program. 

Role-Based Access on AWS EC2 or Other Service

This is the recommended way to grant access to your PHP application within an AWS environment. It removes any need for developers to manage secrets which improves security, ongoing maintenance, and generally fewer headaches. You can grant and manage access to the PHP application by creating and using an IAM role applied to the EC2 or AWS service. This can be done through the console, CLI or infrastructure as code.

Using Credentials from Environment File

The official documentation injects the credentials from the CLI into the process. However, this approach can be overwhelming when you have many environmental variables. To tackle that, we will use a .env file, a plain text file that would include the credentials.

Note: Never push the .env file to source code repositories.

Here’s an example of a .env file.

AWS_ACCESS_KEY_ID=MY_AWS_ACCESS_KEY
AWS_SECRET_ACCESS_KEY=MY_AWS_SECRET_ACCESS_KEY

But before doing that, we need a PHP package that helps us read the .env file and make it accessible in the program. So, let’s install that package via Composer.

composer require vlucas/phpdotenv

You can load the environment variables from the .env file using the following in your program.

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

The environment variables are now accessible to the program. You can access them via $_ENV or getenv()

Using AWS Credential Files and AWS Profiles

A credential file is a plain text file configured via AWS CLI. The aws configure command creates a .aws folder with a credential file.

On UNIX-based systems, .aws is usually located in $HOME. On Windows, find it in your user folder or type %UserProfile% in the run to open up this directory.

Here’s an example of a typical credential file.

[default]
aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY

[profile]
aws_access_key_id = ANOTHER_AWS_ACCESS_KEY_ID
aws_secret_access_key = ANOTHER_AWS_SECRET_ACCESS_KEY

SDK resorts to the default if no credentials or profile is explicitly passed in or defined in the .env file.

Why AWS Credential Files?

Though it is totally up to you to use either of these two options, this article uses the AWS Credential file for these reasons.

  1. The credential file is located outside the project, significantly reducing the chances of any security mishap. For instance – accidentally push the .env file to a repository.
  2. You can define multiple profiles all in one place.
  3. You can reuse these credentials across different projects.
  4. Easy to switch to role-based access if you use or will be switching to EC2

Basic Usage | PHP AWS SDK

You can do countless things via AWS SDK, which has been documented here. However, we will pick AWS S3 and do the following to demonstrate the basic usage of AWS SDK in PHP.

  1. Create an S3 Bucket
  2. Put an Object in the S3 Bucket
  3. Delete the S3 Bucket

Create an S3 Client

First, we must create an S3Client via SDK that would interact with AWS S3 programmatically. Here’s how to do that.

require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

$s3Client = new S3Client([
    'profile' => 'S3-Sudo-User',
    'region' => 'us-east-1',
    'version' => 'lastest'
]);

Observe that we have not explicitly passed AWS credentials because the SDK is smart enough to pick that from the credential files in the .aws folder. Also, we have provided ‘S3-Sudo-User’ as a profile – we are not using the .env file. 

This user was created via AWS IAM, and this profile has full access to AWS S3.  With all that set, let’s create an S3 Bucket.

Create an S3 Bucket

The following example demonstrates how to create a ‘fuelingphpbucket’ in AWS S3 using SDK.

try {
    $result = $s3Client->createBucket([
        'Bucket' => 'fuelingphpbucket',
    ]);
    print_r('The bucket\'s location is: ' .
        $result['Location'] . '. ' .
        'The bucket\'s effective URI is: ' .
        $result['@metadata']['effectiveUri']);
} catch (AwsException $e) {
    print_r('Error: ' . $e->getAwsErrorMessage());
}

Running this program returns the following output.

The bucket's location is: /fuelingphpbucket. 
The bucket's effective URI is: https://fuelingphpbucket.s3.amazonaws.com/

Let’s see that via the AWS console as well.

AWS SDK for PHP
S3 Bucket

Put an Object in the S3 Bucket

Let’s upload the FuelingPHP logo to the S3 bucket we have just created.

AWS SDK for PHP
FuelingPHP Logo
try {
    $result = $s3Client->putObject([
        'Key' => 'fuelingphplogo',
        'Bucket' => 'fuelingphpbucket',
        'ACL' => 'public-read',
        'SourceFile' => './fuelingphplogo.PNG',
        'Expires' => '1h'
    ]);
    print_r(
        'The object\'s URL is: ' .
        $result['ObjectURL']);
} catch (AwsException $e) {
    print_r('Error: ' . $e->getAwsErrorMessage());
}

The ‘Key’ and ‘Bucket’ arguments are required. This example created an object with a publicly accessible URL.

The output is as follows.

The object's URL is: https://fuelingphpbucket.s3.amazonaws.com/fuelingphplogo

Clicking on the URL opens up the logo. However, you cannot open it because we will delete this bucket in the next section.

Delete the S3 Bucket

We need to delete all the objects first before deleting the bucket. So, the following example deletes the object and then deletes the bucket.

try {
    $s3Client->deleteObjects([
        'Bucket' => 'fuelingphpbucket',
        'Delete' => [
            'Objects' => [
                [
                    'Key' => 'fuelingphplogo',
                ],
           
            ]]
    ]);
 
    $s3Client->deleteBucket([
        'Bucket' => 'fuelingphpbucket',
    ]);
 
} catch (AwsException $e) {
    print_r('Error: ' . $e->getAwsErrorMessage());
}

Voila! I assume much has been clear about installing and using AWS SDK in PHP.

Conclusion

This article demonstrates how to install and use AWS SDK for PHP. The article walks you through the initial steps of installing SDK and setting up credentials. Followed by these, the article guides you through some basic examples. These examples use AWS S3 to create a bucket, upload an object to it and then finally delete the object and the bucket.

Hope you’ve found this article valuable. To learn more, stay tuned at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


© 2022 Confident.Systems