amazonwebservices/aws-sdk-for-php
Official AWS SDK for PHP. Build PHP apps that integrate with Amazon Web Services, including S3, DynamoDB, SNS/SQS, CloudWatch, Lambda and more. Supports modern auth/signing, retries, pagination, and async operations.
Installation Add the package via Composer (note: deprecated, but may still be used in legacy projects):
composer require amazonwebservices/aws-sdk-for-php:^1.0
Verify vendor/aws/aws-sdk-php exists in your project.
First Use Case: S3 File Upload
Initialize the SDK in config/services.php:
'aws' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
Use in a controller:
use Aws\S3\S3Client;
$s3 = new S3Client([
'version' => 'latest',
'region' => config('services.aws.region'),
'credentials' => [
'key' => config('services.aws.key'),
'secret' => config('services.aws.secret'),
]
]);
$s3->putObject([
'Bucket' => 'your-bucket',
'Key' => 'file.txt',
'Body' => fopen('local-file.txt', 'r')
]);
Key Files to Review
vendor/aws/aws-sdk-php/src/Aws (core classes)vendor/aws/aws-sdk-php/examples (legacy examples)config/services.php (credentials setup)Service Integration Use dependency injection for AWS services:
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->singleton(S3Client::class, function ($app) {
return new S3Client($app['config']['services.aws']);
});
}
Inject into controllers:
public function __construct(S3Client $s3) {
$this->s3 = $s3;
}
Async Operations Use promises for long-running tasks (e.g., batch processing):
$promise = $s3->registerBucket([
'Bucket' => 'new-bucket',
'CreateBucketConfiguration' => ['LocationConstraint' => 'us-west-2']
]);
$promise->then(function ($result) {
// Handle success
})->wait();
Error Handling Centralize AWS exceptions in a middleware:
// app/Exceptions/Handler.php
public function render($request, Throwable $exception)
{
if ($exception instanceof Aws\AwsException) {
return response()->json([
'error' => 'AWS Service Error',
'code' => $exception->getAwsErrorCode(),
'message' => $exception->getMessage()
], 500);
}
return parent::render($request, $exception);
}
Configuration Management
Extend Aws\Common\Credentials\CredentialsInterface for dynamic credentials:
class TemporaryCredentials extends CredentialsInterface {
public function getCredentials() {
return [
'key' => env('TEMP_AWS_KEY'),
'secret' => env('TEMP_AWS_SECRET'),
];
}
}
Use in SDK initialization:
$s3 = new S3Client([
'credentials' => new TemporaryCredentials()
]);
Deprecation Warnings
aws/aws-sdk-php (v3+) for new projects.Aws\Common\Exception\ExceptionInterface (use Aws\Exception\AwsException in v3).Aws\Common\Credentials\ChainCredentials (replaced by Aws\Credentials\Credentials in v3).Region-Specific Quirks
us-east-1 defaults) may cause issues in non-US regions.LocationConstraint for buckets:
$s3->createBucket([
'Bucket' => 'my-bucket',
'CreateBucketConfiguration' => ['LocationConstraint' => 'eu-west-1']
]);
Memory Limits
getObject) may hit PHP’s memory_limit.$result = $s3->getObject([
'Bucket' => 'bucket',
'Key' => 'large-file.zip'
]);
$stream = $result['Body'];
file_put_contents('local-file.zip', $stream);
Credential Caching
ChainCredentials) are not cached by default.Aws\Common\Credentials\CredentialsInterface with caching logic:
class CachedCredentials implements CredentialsInterface {
private $credentials;
private $ttl;
public function __construct($credentials, $ttl = 3600) {
$this->credentials = $credentials;
$this->ttl = $ttl;
}
public function getCredentials() {
return $this->credentials; // Add TTL logic here
}
}
Enable Debugging
Use the Aws\Common\Logger\LoggerChain to log requests/responses:
use Aws\Common\Logger\LoggerChain;
use Aws\Common\Logger\StreamHandler;
$logger = new LoggerChain([
new StreamHandler(fopen('php://stdout', 'w'), LoggerInterface::DEBUG)
]);
$s3 = new S3Client([
'logger' => $logger,
// ... other config
]);
Common Errors & Fixes
| Error | Cause | Solution |
|---|---|---|
InvalidAccessKeyId |
Wrong credentials | Verify AWS_ACCESS_KEY_ID in .env |
SignatureDoesNotMatch |
Expired/incorrect secret | Regenerate AWS_SECRET_ACCESS_KEY |
NoSuchBucket |
Bucket doesn’t exist | Check region/bucket name case sensitivity |
RequestTimeout |
Slow network/large payload | Increase timeout in SDK config |
Testing
Aws\Common\Credentials\CredentialsInterface mocks in PHPUnit:
$mockCredentials = $this->createMock(CredentialsInterface::class);
$mockCredentials->method('getCredentials')->willReturn([
'key' => 'test-key',
'secret' => 'test-secret'
]);
$s3 = new S3Client([
'credentials' => $mockCredentials,
'region' => 'us-east-1',
'version' => 'latest'
]);
Aws\Common\ServiceAbstract:
$mockS3 = $this->getMockBuilder(S3Client::class)
->disableOriginalConstructor()
->onlyMethods(['putObject'])
->getMock();
$mockS3->expects($this->once())
->method('putObject')
->with(['Bucket' => 'test', 'Key' => 'file.txt']);
Custom Middleware
Extend Aws\Common\Middleware\MiddlewareStack to add pre/post-processing:
class LoggingMiddleware implements MiddlewareInterface {
public function __invoke($request, $handler) {
// Log request
$response = $handler($request);
// Log response
return $response;
}
}
Register in SDK:
$s3 = new S3Client([
'middleware' => [
new LoggingMiddleware(),
// ... other middleware
]
]);
Plugin System
Use Aws\Common\Plugin\PluginInterface to extend functionality:
class CustomPlugin implements PluginInterface {
public function register(Aws\Common\Aws $aws) {
$aws->register('customService', function () {
return new CustomService();
});
}
}
Attach to SDK:
$s3 = new S3Client([
'plugins' => [new CustomPlugin()]
]);
Legacy Migration Helper For transitioning to v3, create a wrapper class:
class V1ToV3Adapter {
private $v3Client;
public function __construct($config) {
$this->v3Client = new Aws\S3\S3Client($config);
}
public function putObject($params) {
return $this->v3Client->putObject($params);
}
// Delegate other methods...
}
How can I help you explore Laravel packages today?