AWS S3 with Symfony

AWS S3

In some situations, we need to use a static storage server. This can make your Web pages much faster. Amazon Simple Storage Service or Amazon S3 is one of the best object storage service. This means your data is protected against failures, errors, and threats. S3 also allows us to block public access to your objects. It automatically creates and stores copies of all S3 objects across multiple systems. There is no limit to the number of objects an user can store in a bucket.

Configurations

First, we need to make our IAM profile to get the Access Keys (create access credentials).
To use S3 bucket in Symfony you need to install aws-sdk-php library. The AWS SDK for PHP makes it easy for developers to access Amazon Web Services in their PHP code (requirements: PHP >= 5.5).

To install this library in applications using Symfony flex, run the following command:

composer require aws/aws-sdk-php

Next, we will have to change default configuration. We need to assign our AWS key, secret, bucket, and region.

parameters:
    amazon.s3.key:     "your-aws-key"
    amazon.s3.secret:  "your-aws-secret"
    amazon.s3.bucket:  "your-bucket.example.com"
    amazon.s3.region:  "your-bucket-region"
    amazon.s3.version: "2006-03-01"

To use SDK we need to make S3 client. Configuration the S3Clinet service in service.yam

acme.amazon_s3:
  class: Aws\S3\S3Client
  factory: [Aws\S3\S3Client, factory]
  arguments:
    -
      credentials: { key: "s3-key", secret:"s3-secret" }
      region: us-east-2
      version: latest

Usage

Example of uploading the file on Amazon S3:

use Aws\Credentials\CredentialProvider;
use Aws\Exception\AwsException;
use Aws\S3\S3Client;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;

$bucket = getenv('S3_BUCKET');
$fileName = md5(uniqid($bucket . '_', false)) . '.' . $this->uploadedFile->guessExtension();


$this->uploadedFile->move($this->tmpFolderPath, $fileName);


try {
  $s3Client = new S3Client([
    'region' => 'us-east-2',
    'version' => 'latest',
    'credentials' => CredentialProvider::env() 
  ]);

  $s3Client->putObject([
    'Bucket' => $bucket,
    'Key' => $fileName,
    'SourceFile' => $this->tmpFolderPath . $fileName,
  ]);

} catch (AwsException $e) {
  echo $e->getMessage() . "\n";
  return false;
}

Get your file from the private bucket:

try {
  return $this->s3Client->getObject(
    [
      'Bucket' => $this→privateBucketName,
      'Key' => $documentName
    ]
  );
} catch(S3Exception $e) { 
  //Hendle your exception here 
}