13/06/2018 - PHP, SYMFONY
If you wish to download files from AWS S3 buckets within Symfony applications by using AWS SDK for PHP library, you can use example below. In this example we are going to download an image file. For more details read Get an Object Using the AWS SDK for PHP page.
# User: These credentials belong to "AmazonS3FullAccess" user.
AWS_KEY=AMAZON000KEY
AWS_SECRET=AMAZON000SECRET
AWS_IMAGE_BUCKET=my-images-bucket
parameters:
# AWS SDK
aws_sdk:
version: 'latest'
region: 'eu-west-2'
credentials:
key: '%env(AWS_KEY)%'
secret: '%env(AWS_SECRET)%'
services:
_defaults:
autowire: true
autoconfigure: true
public: false
...
Aws\Sdk:
arguments:
- '%aws_sdk%'
declare(strict_types=1);
namespace App\Util\Aws;
use Aws\Sdk;
abstract class AwsUtil
{
protected $sdk;
public function __construct(Sdk $sdk)
{
$this->sdk = $sdk;
}
}
declare(strict_types=1);
namespace App\Util\Aws;
use App\Exception\AwsUtilException;
use Aws\S3\Exception\S3Exception;
use GuzzleHttp\Psr7\Stream;
class AwsS3Util extends AwsUtil
{
public function getObject(string $bucket, string $key): Stream
{
try {
$result = $this->sdk->createS3()->getObject(['Bucket' => $bucket, 'Key' => $key]);
return $result['Body'];
} catch (S3Exception $e) {
throw new AwsUtilException($e->getMessage());
}
}
}
Assume that the image URL is something like these: https://s3.eu-west-2.amazonaws.com/my-images-bucket/images/in/an/zz/zz/1234567890qwerty.jpg
or https://myimages.amazonaws.com/my-images-bucket/images/in/an/zz/zz/1234567890qwerty.jpg
. Use line below to download the image.
AwsS3Util->getObject('my-images-bucket', 'images/in/an/zz/zz/1234567890qwerty.jpg');