Configuring AWS SDK for PHP with S3

Fernando Muller Junior - Aug 25 - - Dev Community

Amazon Web Services (AWS) is a powerful platform that offers a wide range of services for developers and businesses. Among these services, Amazon Simple Storage Service (S3) is one of the most popular and widely used. To interact with S3 programmatically, you can use the AWS SDK for PHP. In this article, we will guide you through the process of configuring the AWS SDK for PHP with S3.

php with aws

Prerequisites

Before we begin, make sure you have the following:

  • An AWS account
  • AWS Access Key ID and Secret Access Key
  • PHP 5.6 or higher
  • Composer installed

Installation

To install the AWS SDK for PHP, you can use Composer. Run the following command in your terminal:

composer require aws/aws-sdk-php
Enter fullscreen mode Exit fullscreen mode

This command will install the latest version of the AWS SDK for PHP in your project.

Configuration

Once you have installed the SDK, you need to configure it with your AWS Access Key ID and Secret Access Key. You can do this by creating a configuration file or by setting environment variables.

Configuration File

Create a new file named config.php in your project and add the following code:

<?php
require 'vendor/autoload.php';

use Aws\Sdk;

$sdk = new Sdk([
    'region' => 'us-east-1',
    'version' => 'latest',
    'credentials' => [
        'key' => 'YOUR_ACCESS_KEY_ID',
        'secret' => 'YOUR_SECRET_ACCESS_KEY',
    ]
]);

$s3Client = $sdk->createS3();
Enter fullscreen mode Exit fullscreen mode

Replace YOUR_ACCESS_KEY_ID and YOUR_SECRET_ACCESS_KEY with your actual AWS Access Key ID and Secret Access Key.

Environment Variables

Alternatively, you can set the AWS Access Key ID and Secret Access Key as environment variables:

export AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID
export AWS_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY
Enter fullscreen mode Exit fullscreen mode

Then, create the S3 client as follows:

<?php
require 'vendor/autoload.php';

use Aws\Sdk;

$sdk = new Sdk([
    'region' => 'us-east-1',
    'version' => 'latest',
]);

$s3Client = $sdk->createS3();
Enter fullscreen mode Exit fullscreen mode

Ready to learn more about AWS and PHP? Check out our other articles on AWS configure SSO and Fixing laravel permission denied errors.

Usage

Now that you have configured the AWS SDK for PHP with S3, you can start using it to interact with your S3 buckets. Here's an example of how to list all the buckets in your account:

$buckets = $s3Client->listBuckets();
foreach ($buckets['Buckets'] as $bucket) {
    echo $bucket['Name'] . PHP_EOL;
}
Enter fullscreen mode Exit fullscreen mode

Sure, here are some additional examples and best practices for using the AWS SDK for PHP with S3.

Uploading a File

To upload a file to an S3 bucket, you can use the putObject method. Here's an example:

$bucketName = 'my-bucket';
$keyName = 'my-file.txt';
$filePath = '/path/to/my-file.txt';

$result = $s3Client->putObject([
    'Bucket' => $bucketName,
    'Key' => $keyName,
    'SourceFile' => $filePath,
]);

echo $result['ObjectURL'] . PHP_EOL;
Enter fullscreen mode Exit fullscreen mode

This code will upload the file located at /path/to/my-file.txt to the my-bucket bucket and print the URL of the uploaded file.

Downloading a File

To download a file from an S3 bucket, you can use the getObject method. Here's an example:

$bucketName = 'my-bucket';
$keyName = 'my-file.txt';
$filePath = '/path/to/downloaded-file.txt';

$result = $s3Client->getObject([
    'Bucket' => $bucketName,
    'Key' => $keyName,
    'SaveAs' => $filePath,
]);

echo $result['ContentLength'] . ' bytes downloaded.' . PHP_EOL;
Enter fullscreen mode Exit fullscreen mode

This code will download the file with the key my-file.txt from the my-bucket bucket and save it to /path/to/downloaded-file.txt.

Listing Objects

To list the objects in an S3 bucket, you can use the listObjects method. Here's an example:

$bucketName = 'my-bucket';

$result = $s3Client->listObjects([
    'Bucket' => $bucketName,
]);

foreach ($result['Contents'] as $object) {
    echo $object['Key'] . PHP_EOL;
}
Enter fullscreen mode Exit fullscreen mode

This code will list all the objects in the my-bucket bucket and print their keys.

Best Practices - AWS SDK + PHP + S3

Here are some best practices to keep in mind when using the AWS SDK for PHP with S3:

  • Use IAM roles and policies to manage access to your S3 resources.
  • Use versioning to keep multiple versions of your objects and protect against accidental deletion.
  • Use lifecycle policies to automatically manage the storage and retention of your objects.
  • Use transfer acceleration to improve the performance of your uploads and downloads.
  • Use server-side encryption to protect your data at rest.
  • Use event notifications to trigger actions based on changes to your S3 objects.

Sure, here are some additional tips for using the AWS SDK for PHP with S3 in Laravel.

Using the AWS SDK for PHP with Laravel

Laravel has built-in support for the AWS SDK for PHP, which makes it easy to use S3 in your Laravel applications. Here are some tips for using the SDK with Laravel:

  • Install the AWS SDK for PHP package via Composer:
composer require aws/aws-sdk-php
Enter fullscreen mode Exit fullscreen mode
  • Configure your AWS credentials in your .env file:
AWS_ACCESS_KEY_ID=your_access_key_id
AWS_SECRET_ACCESS_KEY=your_secret_access_key
AWS_DEFAULT_REGION=your_region
Enter fullscreen mode Exit fullscreen mode
  • Use the Storage facade to interact with S3:
use Illuminate\Support\Facades\Storage;

// Upload a file
Storage::disk('s3')->put('my-file.txt', file_get_contents('/path/to/my-file.txt'));

// Download a file
Storage::disk('s3')->download('my-file.txt', '/path/to/downloaded-file.txt');

// List the objects in a bucket
$objects = Storage::disk('s3')->listContents('my-bucket');

foreach ($objects as $object) {
    echo $object['path'] . PHP_EOL;
}
Enter fullscreen mode Exit fullscreen mode
  • Use Laravel's Flysystem adapter to customize the behavior of the Storage facade:
use Illuminate\Support\ServiceProvider;
use League\Flysystem\AwsS3V3\AwsS3V3Adapter;
use Aws\S3\S3Client;

class S3ServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('filesystems.disks.s3', function ($app) {
            return new AwsS3V3Adapter(
                new S3Client([
                    'region' => config('filesystems.disks.s3.region'),
                    'version' => 'latest',
                    'credentials' => [
                        'key' => config('filesystems.disks.s3.key'),
                        'secret' => config('filesystems.disks.s3.secret'),
                    ],
                ]),
                config('filesystems.disks.s3.bucket')
            );
        });
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Use Laravel's queue system to perform S3 operations asynchronously:
use Illuminate\Support\Facades\Storage;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class UploadFile implements ShouldQueue
{
    use InteractsWithQueue;

    protected $filePath;

    public function __construct($filePath)
    {
        $this->filePath = $filePath;
    }

    public function handle()
    {
        Storage::disk('s3')->put('my-file.txt', file_get_contents($this->filePath));
    }
}
Enter fullscreen mode Exit fullscreen mode

Best Practices - AWS SDK + PHP + Laravel

Here are some best practices to keep in mind when using the AWS SDK for PHP with S3 in Laravel:

  • Use Laravel's built-in support for the AWS SDK for PHP to simplify your code and reduce the amount of boilerplate code you need to write.
  • Use Laravel's queue system to perform S3 operations asynchronously, which can improve the performance and scalability of your Laravel applications.
  • Use Laravel's Flysystem adapter to customize the behavior of the Storage facade and to integrate S3 with other Laravel features, such as Laravel's cache system.
  • Use Laravel's queue system to perform S3 operations asynchronously, which can improve the performance and scalability of your Laravel applications.
  • Use Laravel's encryption features to encrypt sensitive data before storing it in S3.
  • Use Laravel's logging features to log any errors or exceptions that occur when using the AWS SDK for PHP with S3.

Conclusion

In this article, we have covered the basics of configuring the AWS SDK for PHP with S3 and provided some additional examples and best practices for using the SDK with S3. We have also provided some additional tips for using the SDK with S3 in Laravel. By following these guidelines, you can ensure that your PHP applications are secure, efficient, and scalable.


Want to learn more about AWS and PHP? Check out our other articles on DevOps Mind.

. . . . . . . . . . . . . . . . . . . . . . . . . . . .