aws/aws-sdk-php
AWS SDK for PHP v3 provides PHP 8.1+ clients for Amazon Web Services like S3, DynamoDB, Glacier, and more. Install via Composer and use the included service APIs to authenticate, send requests, and build robust AWS-powered applications.
## Getting Started
### Minimal Steps for Laravel Integration
1. **Install the SDK**
```bash
composer require aws/aws-sdk-php
Laravel developers often pair this with the official AWS SDK Laravel package for seamless integration with Laravel's service container.
Configure AWS Credentials
Store credentials in .env (recommended) or config/aws.php:
AWS_ACCESS_KEY_ID=your_key
AWS_SECRET_ACCESS_KEY=your_secret
AWS_DEFAULT_REGION=us-west-2
Use Laravel's config('services.aws') to access these values.
First Use Case: Upload to S3
use Aws\S3\S3Client;
use Illuminate\Support\Facades\Storage;
$s3 = new S3Client(config('services.aws'));
$s3->putObject([
'Bucket' => 'my-bucket',
'Key' => 'file.txt',
'Body' => Storage::disk('local')->get('file.txt'),
'ACL' => 'public-read',
]);
Leverage Laravel's service container to bind the SDK client:
// config/app.php
'providers' => [
Aws\Sdk\Laravel\AwsServiceProvider::class,
],
Access clients via:
$s3 = app('aws')->createS3();
$dynamodb = app('aws')->createDynamoDb();
Enable the S3 stream wrapper in config/filesystems.php:
'disks' => [
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'bucket' => env('AWS_BUCKET'),
'region' => env('AWS_REGION'),
'url' => env('AWS_URL'),
],
],
Now use PHP's native file functions:
file_put_contents('s3://my-bucket/file.txt', 'Hello, S3!');
Use paginators for large datasets (e.g., S3 list objects):
$objects = $s3->getPaginator('listObjects', [
'Bucket' => 'my-bucket',
]);
foreach ($objects as $page) {
foreach ($page['Contents'] as $object) {
// Process each object
}
}
Use waiters for async operations (e.g., DynamoDB table creation):
$waiter = $dynamodb->getWaiter('tableExists');
$waiter->wait(['TableName' => 'my-table']);
Add Guzzle middleware for debugging:
$s3 = new S3Client([
'region' => 'us-west-2',
'http' => [
'middleware' => [
new Aws\Guzzle\Middleware::tap(function ($request) {
Laravel\Log::debug('S3 Request:', $request->toPsr7());
}),
],
],
]);
Offload heavy AWS operations to queues:
use Aws\S3\S3Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
class UploadToS3 implements ShouldQueue
{
use Queueable;
public function handle(S3Client $s3)
{
$s3->putObject([/* ... */]);
}
}
Use IAM roles (for EC2) or temporary credentials (via Aws\Credentials\Credentials):
$client = new S3Client([
'credentials' => Aws\Credentials\Credentials::fromCredentialsProvider(
new Aws\Credentials\TemporaryCredentialsProvider([
'key' => 'ASIA...',
'secret' => '...',
'token' => '...',
])
),
]);
Credential Leaks
.env or AWS IAM roles..aws/credentials or config/aws.php to version control.Region Mismatches
region in your client matches the AWS service's region. Example:
$client = new S3Client(['region' => 'eu-central-1']); // Not us-west-2!
Rate Limiting
$client = new S3Client([
'http' => [
'retry' => [
'max_attempts' => 5,
'delay' => 200, // ms
],
],
]);
Stream Wrapper Quirks
s3://) may not support all PHP file functions (e.g., file_get_contents for large files). Use the SDK's getObject instead:
$result = $s3->getObject(['Bucket' => 'my-bucket', 'Key' => 'large-file.zip']);
file_put_contents('local-file.zip', $result['Body']);
DynamoDB Session Handler
DynamoDbSessionHandler requires a DynamoDB table with a specific schema. Migrate existing sessions manually if switching from file-based storage.Enable Wire Logging Add this to your client config to log raw HTTP requests/responses:
$client = new S3Client([
'debug' => true,
'http' => [
'stream' => fopen('php://temp', 'w+'),
],
]);
Validate IAM Permissions Use the AWS CLI to test permissions before coding:
aws s3 ls s3://my-bucket --profile my-profile
Check for Deprecated Methods
The SDK evolves rapidly. Use php artisan ide-helper:generate to auto-complete and catch deprecations.
Custom Middleware Extend Guzzle middleware for pre/post-processing:
$client = new S3Client([
'http' => [
'middleware' => [
new class implements Aws\Guzzle\Middleware {
public function __invoke($request, $handler) {
// Modify request
return $handler($request);
}
},
],
],
]);
Service-Specific Helpers Create Laravel helpers for common operations:
// app/Services/S3Service.php
class S3Service {
public function __construct(private S3Client $s3) {}
public function uploadFromLocal(string $path, string $bucket, string $key) {
return $this->s3->putObject([
'Bucket' => $bucket,
'Key' => $key,
'Body' => fopen($path, 'r'),
]);
}
}
Event Listeners for AWS Events Use the SDK's event system to react to service changes:
$client = new S3Client([
'events' => [
'aws.s3.*' => function ($event) {
Log::info('S3 Event:', $event->getName());
},
],
]);
Reuse Clients Instantiate clients once (e.g., in Laravel's service container) and reuse them:
// config/app.php
'bindings' => [
S3Client::class => function () {
return new S3Client(config('services.aws'));
},
];
Parallel Requests
Use Guzzle's Promise for concurrent operations:
$promises = [];
foreach ($keys as $key) {
$promises[] = $s3->getObject(['Bucket' => 'my-bucket', 'Key' => $key]);
}
$results = Aws\Guzzle\Promise\PromiseUtils::wait($promises);
Transfer Acceleration Enable S3 transfer acceleration for faster uploads/downloads:
$s3 = new S3Client([
'endpoint' => 'my-bucket.s3-accelerate.amazonaws.com',
]);
How can I help you explore Laravel packages today?