AWS SDK for PHP
Developer Guide
AWS SDK for PHP: Developer Guide
Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon.
Table of Contents
AWS SDK for PHP ... 1
Getting Started ... 1
SDK Guides ... 1
Service-Specific Features ... 1
Examples ... 2
Reference ... 2
API Documentation ... 2
Maintenance and support for SDK major versions ... 2
Getting Started ... 3
Prerequisites ... 3
Requirements ... 3
Recommendations ... 3
Compatibility Test ... 4
Installing the SDK ... 4
Install AWS SDK for PHP as a dependency via Composer ... 4
Installing by Using the Packaged Phar ... 5
Installing by Using the ZIP file ... 5
Basic Usage ... 6
Prerequisites ... 6
Including the SDK in Your Code ... 6
Usage Summary ... 6
Creating a Client ... 6
Using the Sdk Class ... 7
Executing Service Operations ... 8
Asynchronous Requests ... 9
Working with Result Objects ... 10
Handling Errors ... 11
Upgrading from Version 2 ... 13
Introduction ... 13
What’s New in Version 3? ... 13
What’s Different from Version 2? ... 14
Comparing Code Samples from Both Versions of the SDK ... 19
Configuring the SDK ... 22
Configuration Options ... 22
api_provider ... 23
credentials ... 23
debug ... 24
stats ... 26
endpoint ... 27
endpoint_provider ... 27
endpoint_discovery ... 28
handler ... 29
http ... 29
http_handler ... 35
profile ... 36
region ... 36
retries ... 36
scheme ... 38
service ... 39
signature_provider ... 39
signature_version ... 39
ua_append ... 40
use_aws_shared_config_files ... 40
validate ... 40
version ... 41
Setting Credentials ... 41
Using the Default Credential Provider Chain ... 42
Other Ways to Add Credentials ... 42
Using Credentials from Environment Variables ... 43
Using the AWS Credentials File and Credential Profiles ... 43
Assume an IAM Role ... 45
Using a Credential Provider ... 49
Using Temporary Credentials from AWS STS ... 55
Hard code credentials ... 57
Creating Anonymous Clients ... 57
Command Objects ... 57
Implicit Use of Commands ... 58
Command Parameters ... 58
Creating Command Objects ... 59
Command HandlerList ... 59
CommandPool ... 60
Promises ... 62
What Is a Promise? ... 63
Promises in the SDK ... 63
Chaining Promises ... 64
Waiting on Promises ... 65
Canceling Promises ... 65
Combining Promises ... 66
Handlers and Middleware ... 67
Handlers ... 67
Middleware ... 68
Creating Custom handlers ... 74
Streams ... 74
Stream Decorators ... 74
Paginators ... 77
Paginator Objects ... 78
Enumerating Data from Results ... 78
Asynchronous Pagination ... 79
Waiters ... 79
Waiter Configuration ... 80
Waiting Asynchronously ... 81
JMESPath Expressions ... 82
Extracting Data from Results ... 82
Extracting Data from paginators ... 85
Using AWS Services ... 86
AWS Cloud9 ... 86
Step 1: Set up Your AWS Account to Use AWS Cloud9 ... 86
Step 2: Set up Your AWS Cloud9 Development Environment ... 86
Step 3: Set up the AWS SDK for PHP ... 87
Step 4: Download Example Code ... 87
Step 5: Run and Debug Example Code ... 87
Amazon DynamoDB ... 87
Basic Usage ... 88
Configuration ... 88
Pricing ... 90
Session Locking ... 90
Garbage Collection ... 91
Best Practices ... 91
Required IAM Permissions ... 92
Amazon S3 Multi-Region Client ... 92
Basic Usage ... 88
Bucket Region Cache ... 93
Amazon S3 Stream Wrapper ... 93
Downloading Data ... 94
Uploading Data ... 95
fopen Modes ... 95
Other Object Functions ... 96
Working with Buckets ... 97
Stream Context Options ... 98
Amazon S3 Transfer Manager ... 98
Uploading a Local Directory to Amazon S3 ... 98
Downloading an Amazon S3 Bucket ... 99
Configuration ... 88
Transfer Options ... 100
Async Transfers ... 100
Customizing the Transfer Manager’s Commands ... 101
Amazon S3 Client Side Encryption ... 101
Migration Guide ... 101
Setup ... 102
Encryption ... 102
Decryption ... 103
Cipher Configuration ... 103
Metadata Strategies ... 104
Multipart Uploads ... 105
Code Examples ... 106
Credentials ... 23
Amazon CloudFront Examples ... 106
Managing CloudFront Distributions ... 107
Managing CloudFront Invalidations ... 117
Signing CloudFront URLs ... 120
Amazon CloudSearch ... 126
Credentials ... 23
Sign CSlong Domain Request ... 126
Amazon CloudWatch Examples ... 127
Credentials ... 23
Working with Amazon CloudWatch Alarms ... 128
Getting Metrics from Amazon CloudWatch ... 132
Publishing Custom Metrics in Amazon CloudWatch ... 137
Sending Events to Amazon CloudWatch Events ... 140
Using Alarm Actions with Amazon CloudWatch Alarms ... 142
Amazon EC2 Examples ... 144
Credentials ... 23
Managing Amazon EC2 Instances ... 144
Using Elastic IP Addresses ... 147
Using Regions and Availability Zones ... 149
Working with Key Pairs ... 150
Working with Security Groups ... 152
Amazon Elasticsearch ... 154
Credentials ... 23
Signing an OpenSearch Service Request ... 154
AWS Identity and Access Management Examples ... 155
Credentials ... 23
Managing IAM Access Keys ... 155
Managing IAM Users ... 158
Using IAM Account Aliases ... 161
Working with IAM Policies ... 163
Working with IAM Server Certificates ... 170
AWS Key Management Service ... 173
Working with Keys ... 173
Encrypting and Decrypting Data Keys ... 177
Working with Key Policies ... 180
Working with Grants ... 183
Working with Aliases ... 186
Amazon Kinesis Examples ... 189
Kinesis Data Streams ... 189
Kinesis Shards ... 193
Kinesis Data Firehose Delivery Streams ... 195
AWS Elemental MediaConvertt ... 201
Credentials ... 23
Getting Your Account-Specific Endpoint ... 202
Creating and Managing Jobs ... 203
Amazon S3 Examples ... 208
Credentials ... 23
Creating and Using Amazon S3 Buckets ... 208
Managing Amazon S3 Bucket Access Permissions ... 211
Configuring Amazon S3 Buckets ... 212
Amazon S3 Multipart Uploads ... 214
Creating S3 Pre-Signed POSTs ... 221
Amazon S3 Pre-Signed URL ... 222
Using an Amazon S3 Bucket as a Static Web Host ... 224
Working with Amazon S3 Bucket Policies ... 225
Using S3 Access Point ARNs ... 227
AWS Secrets Manager ... 229
Credentials ... 23
Create a Secret in Secrets Manager ... 229
Retrieve a Secret from Secrets Manager ... 230
List Secrets Stored in Secrets Manager ... 231
Retrieve Details about a Secret ... 232
Update the Secret Value ... 232
Rotate the Value to an Existing Secret in Secrets Manager ... 233
Delete a Secret from Secrets Manager ... 234
Related Information ... 235
Amazon SES Examples ... 235
Verifying Email Addresses ... 236
Working with Email Templates ... 240
Managing Email Filters ... 244
Using Email Rules ... 247
Monitor Your Sending Activity ... 253
Authorizing Senders ... 254
Amazon SNS Examples ... 258
Managing Topics ... 258
Managing Subscriptions ... 262
Sending Amazon SMS Messages ... 267
Amazon SQS Examples ... 271
Enabling Long Polling ... 271
Managing Visibility Timeout ... 274
Sending and Receiving Messages ... 275
Using Dead Letter Queues ... 277
Using Queues ... 278
Security ... 281
Data Protection ... 281
Identity and Access Management ... 282
Compliance Validation ... 282
Resilience ... 283
Infrastructure Security ... 283
S3 Encryption Client Migration ... 283
Migration Overview ... 283
Update Existing Clients to Read New Formats ... 284
Migrate Encryption and Decryption Clients to V2 ... 284
Migration Examples ... 285
FAQ ... 287
What methods are available on a client? ... 287
What do I do about a cURL SSL certificate error? ... 287
What API versions are available for a client? ... 287
What Region versions are available for a client? ... 287
Why can’t I upload or download files larger than 2 GB? ... 288
How can I see what data is sent over the wire? ... 288
How can I set arbitrary headers on a request? ... 288
How can I sign an arbitrary request? ... 288
How can I modify a command before sending it? ... 288
What is a CredentialsException? ... 289
Does the AWS SDK for PHP work on HHVM? ... 289
How do I disable SSL? ... 289
What do I do about a “Parse error”? ... 289
Why is the Amazon S3 client decompressing gzipped files? ... 290
How do I disable body signing in Amazon S3? ... 290
How is retry scheme handled in the AWS SDK for PHP? ... 290
How do I handle exceptions with error codes? ... 291
Glossary ... 292
Additional Resources ... 294
PHP SDK Forum ... 294
PHP SDK on GitHub ... 294
PHP SDK on Gitter ... 294
Document History ... 295
Getting Started
What Is the AWS SDK for PHP Version 3?
The AWS SDK for PHP Version 3 enables PHP developers to use Amazon Web Services in their PHP code, and build robust applications and software using services like Amazon S3, Amazon DynamoDB, S3 Glacier, etc. You can get started in minutes by installing the SDK through Composer — by requiring the aws/aws-sdk-php package — or by downloading the standalone aws.zip or aws.phar file.
Not all services are immediately available in the SDK. To find out which services are currently supported by the AWS SDK for PHP, see Service Name and API Version. For information about the AWS SDK for PHP Version 3 on GitHub, see Additional Resources (p. 294).
NoteIf you’re migrating your code from using Version 2 of the SDK to Version 3, be sure to read Upgrading from Version 2 of the AWS SDK for PHP (p. 13).
Getting Started
• Requirements and Recommendations for the AWS SDK for PHP Version 3 (p. 3)
• Installing the AWS SDK for PHP Version 3 (p. 4)
• Basic Usage Patterns of the AWS SDK for PHP Version 3 (p. 6)
• Upgrading from Version 2 of the AWS SDK for PHP (p. 13)
SDK Guides
• Configuration for the AWS SDK for PHP (p. 22)
• Credentials for the AWS SDK for PHP (p. 41)
• Command Objects in the AWS SDK for PHP (p. 57)
• Promises in the AWS SDK for PHP (p. 62)
• Handlers and Middleware in the AWS SDK for PHP (p. 67)
• Streams in the AWS SDK for PHP (p. 74)
• Paginators in the AWS SDK for PHP (p. 77)
• Waiters in the AWS SDK for PHP (p. 79)
• JMESPath Expressions in the AWS SDK for PHP (p. 82)
Service-Specific Features
• Using AWS Cloud9 with the AWS SDK for PHP (p. 86)
• Using the DynamoDB Session Handler with AWS SDK for PHP (p. 87)
• Amazon S3 Multi-Region Client (p. 92)
• Amazon S3 Stream Wrapper (p. 93)
• Amazon S3 Transfer Manager (p. 98)
Examples
• Amazon S3 Client Side Encryption (p. 101)
Examples
• Amazon CloudFront (p. 106)
• Signing Custom Amazon CloudSearch Domain Requests (p. 126)
• Amazon CloudWatch Examples (p. 127)
• Amazon EC2 (p. 144)
• Signing an Amazon Elasticsearch Service Search Request (p. 154)
• AWS Identity and Access Management Examples (p. 155)
• AWS Key Management Service (p. 173)
• Amazon Kinesis Examples (p. 189)
• AWS Elemental MediaConvert Examples (p. 201)
• Amazon S3 Examples (p. 208)
• Amazon Simple Email Services Examples (p. 235)
• Amazon SNS Examples (p. 258)
• Amazon SQS Examples (p. 271)
For additional examples, see the AWS Code Sample Catalog.
Reference
• FAQ (p. 287)
• Glossary (p. 292)
• Contributing to the SDK
• Guzzle Documentation
Submit issues on GitHub:
• Submit documentation issues
• Report a bug or request a feature
API Documentation
Find API documentation for the SDK at https://docs.aws.amazon.com/sdk-for-php/latest/reference/.
Maintenance and support for SDK major versions
For information about maintenance and support for SDK major versions and their underlying dependencies, see the following in the AWS SDKs and Tools Shared Configuration and Credentials Reference Guide:
• AWS SDKs and Tools Maintenance Policy
• AWS SDKs and Tools Version Support Matrix
Prerequisites
Getting Started with the AWS SDK for PHP Version 3
This chapter is dedicated to getting you up and running with the AWS SDK for PHP Version 3.
Topics
• Requirements and Recommendations for the AWS SDK for PHP Version 3 (p. 3)
• Installing the AWS SDK for PHP Version 3 (p. 4)
• Basic Usage Patterns of the AWS SDK for PHP Version 3 (p. 6)
• Upgrading from Version 2 of the AWS SDK for PHP (p. 13)
Requirements and Recommendations for the AWS SDK for PHP Version 3
For best results with AWS SDK for PHP, ensure your environment supports the following requirements and recommendations.
Requirements
To use the AWS SDK for PHP, you must be using PHP version 5.5.0 or later with the SimpleXML PHP extension enabled. If you need to sign private Amazon CloudWatch URLs, you also need the OpenSSL PHP extension.
Recommendations
In addition to the minimum requirements, we recommend you also install, uninstall, and use the following.
Install cURL 7.16.2 or later Use a recent version of cURL compiled with OpenSSL/NSS and zlib. If cURL isn’t installed on your system and you don’t configure a custom http_handler for your client, the SDK uses the PHP stream wrapper.
Use OPCache Use the OPcache extension to improve PHP
performance by storing precompiled script bytecode in shared memory. This removes the need for PHP to load and parse scripts on each request. This extension is typically enabled by default.
When running Amazon Linux, you need to install the php56-opcache or php55-opcache yum package to use the OPCache extension.
Compatibility Test
Uninstall Xdebug Xdebug can help identify performance
bottlenecks. However, if performance is critical to your application, don’t install the Xdebug extension in your production environment.
Loading the extension slows SDK performance considerably.
Use a Composer classmap autoloader Autoloaders load classes as they are required by a PHP script. Composer generates an autoloader that can autoload the PHP scripts of your application and all other PHP scripts required by your application, including the AWS SDK for PHP.
For production environments, we recommended you use a classmap autoloader to improve autoloader performance. You can generate a classmap autoloader by passing the -o or
==optimize-autoloader option to Composer’s install command.
Compatibility Test
Run the compatibility-test.php file in the SDK to verify your system can run the SDK. In addition to meeting the SDK’s minimum system requirements, the compatibility test checks for optional settings and makes recommendations that can help improve performance. The compatibility test outputs results either to the command line or a web browser. When reviewing test results in a browser, successful checks appear in green, warnings in purple, and failures in red. When running from the command line, the result of a check appears on a separate line.
When reporting an issue with the SDK, sharing the output of the compatibility test helps identify the underlying cause.
Installing the AWS SDK for PHP Version 3
You can install the AWS SDK for PHP Version 3:
• As a dependency via Composer
• As a prepackaged phar of the SDK
• As a ZIP file of the SDK
Before you install AWS SDK for PHP Version 3 ensure your environment is using PHP version 5.5 or later.
Learn more about environment requirements and recommendations (p. 3).
NoteInstalling the SDK via the .phar and .zip methods requires the Multibyte String PHP extension to be installed and enabled separately.
Install AWS SDK for PHP as a dependency via Composer
Composer is the recommended way to install the AWS SDK for PHP. Composer is a tool for PHP that manages and installs the dependencies of your project.
Installing by Using the Packaged Phar
For more information on how to install Composer, configure autoloading, and follow other best practices for defining dependencies, see getcomposer.org.
Install Composer
If Composer is not already in your project, download and install Composer.
For Windows, download and run the Composer-Setup.exe.
For Linux, follow the Command-line installation on the Download Composer page.
Add AWS SDK for PHP as a dependency via Composer
If Composer is already installed globally on your system, run the following in the base directory of your project to install AWS SDK for PHP as a dependency:
composer require aws/aws-sdk-php
Otherwise type this Composer command to install the latest version of the AWS SDK for PHP as a dependency.
php -d memory_limit=-1 composer.phar require aws/aws-sdk-php
Add autoloader to your php scripts
To utilize the AWS SDK for PHP in your scripts, include the autoloader in your scripts, as follows.
<?php
require '/path/to/vendor/autoload.php';
?>
Installing by Using the Packaged Phar
Each release of the AWS SDK for PHP includes a prepackaged phar (PHP archive) that contains all the classes and dependencies you need to run the SDK. Additionally, the phar automatically registers a class autoloader for the AWS SDK for PHP and all its dependencies.
You can download the packaged phar and include it in your scripts.
<?php
require '/path/to/aws.phar';
?>
NoteUsing PHP with the Suhosin patch is not recommended, but is common on Ubuntu and Debian distributions. In this case, you might need to enable the use of phars in the suhosin.ini. If you don’t do this, including a phar file in your code will cause a silent failure. To modify suhosin.ini, add the following line.
suhosin.executor.include.whitelist = phar
Installing by Using the ZIP file
The AWS SDK for PHP includes a ZIP file containing all the classes and dependencies you need to run the SDK. Additionally, the ZIP file includes a class autoloader for the AWS SDK for PHP and its dependencies.
Basic Usage
To install the SDK, download the .zip file, and then extract it into your project at a location you choose.
Then include the autoloader in your scripts, as follows.
<?php
require '/path/to/aws-autoloader.php';
?>
Basic Usage Patterns of the AWS SDK for PHP Version 3
This topic focuses on basic usage patterns of the AWS SDK for PHP.
Prerequisites
• Download and installed the SDK (p. 4)
• Retrieve your AWS access keys.
Including the SDK in Your Code
No matter which technique you used to install the SDK, you can include the SDK in your code with just a single require statement. See the following table for the PHP code that best fits your installation technique. Replace any instances of /path/to/ with the actual path on your system.
Installation Technique Require Statement
Using Composer require '/path/to/vendor/
autoload.php';
Using the phar require '/path/to/aws.phar';
Using the ZIP require '/path/to/aws-autoloader.php';
In this topic, we show examples that assume the Composer installation method. If you’re using a different installation method, you can refer back to this section to find the correct require code to use.
Usage Summary
To use the SDK to interact with an AWS service, instantiate a Client object. Client objects have methods that correspond one to one with operations in the service’s API. To execute a particular operation, you call its corresponding method. This method either returns an array-like Result object on success, or throws an Exception on failure.
Creating a Client
You can create a client by passing an associative array of options to a client’s constructor.
Imports
require 'vendor/autoload.php';
Using the Sdk Class
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
Sample Code
//Create a S3Client
$s3 = new Aws\S3\S3Client([
'version' => 'latest', 'region' => 'us-east-2' ]);
Notice that we did not explicitly provide credentials to the client. That’s because the SDK should detect the credentials from environment variables (p. 43) (via AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY), an AWS credentials INI file (p. 43) in your HOME directory, AWS Identity and Access Management (IAM) instance profile credentials (p. 45), or credential providers (p. 49).
All of the general client configuration options are described in detail in the configuration
guide (p. 22). The array of options provided to a client can vary based on which client you’re creating.
These custom client configuration options are described in the API documentation for each client.
Using the Sdk Class
The Aws\Sdk class acts as a client factory and is used to manage shared configuration options across multiple clients. The same options that can be provided to a specific client constructor can also be supplied to the Aws\Sdk class. These options are then applied to each client constructor.
Imports
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
Sample Code
// The same options that can be provided to a specific client constructor can also be supplied to the Aws\Sdk class.
// Use the us-west-2 region and latest version of each client.
$sharedConfig = [
'region' => 'us-west-2', 'version' => 'latest' ];
// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk($sharedConfig);
// Create an Amazon S3 client using the shared configuration data.
$client = $sdk->createS3();
Options that are shared across all clients are placed in root-level key-value pairs. Service-specific configuration data can be provided in a key that is the same as the namespace of a service (e.g., “S3”,
“DynamoDb”, etc.).
$sdk = new Aws\Sdk([
'region' => 'us-west-2', 'version' => 'latest',
Executing Service Operations
'DynamoDb' => [
'region' => 'eu-central-1' ]
]);
// Creating an Amazon DynamoDb client will use the "eu-central-1" AWS Region
$client = $sdk->createDynamoDb();
Service-specific configuration values are a union of the service-specific values and the root-level values (i.e., service-specific values are shallow-merged onto root-level values).
NoteWe highly recommended that you use the Sdk class to create clients if you’re using multiple client instances in your application. The Sdk class automatically uses the same HTTP client for each SDK client, allowing SDK clients for different services to perform nonblocking HTTP requests. If the SDK clients don’t use the same HTTP client, then HTTP requests sent by the SDK client might block promise orchestration between services.
Executing Service Operations
You can execute a service operation by calling the method of the same name on a client object. For example, to perform the Amazon S3 PutObject operation, you must call the Aws
\S3\S3Client::putObject() method.
Imports
require 'vendor/autoload.php';
use Aws\S3\S3Client;
Sample Code
// Use the us-east-2 region and latest version of each client.
$sharedConfig = [
'profile' => 'default', 'region' => 'us-east-2', 'version' => 'latest' ];
// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk($sharedConfig);
// Use an Aws\Sdk class to create the S3Client object.
$s3Client = $sdk->createS3();
// Send a PutObject request and get the result object.
$result = $s3Client->putObject([
'Bucket' => 'my-bucket', 'Key' => 'my-key',
'Body' => 'this is the body!' ]);
// Download the contents of the object.
$result = $s3Client->getObject([
'Bucket' => 'my-bucket', 'Key' => 'my-key' ]);
// Print the body of the result by indexing into the result object.
echo $result['Body'];
Asynchronous Requests
Operations available to a client and the structure of the input and output are defined at runtime based on a service description file. When creating a client, you must provide a version (e.g., “2006-03-01” or
“latest”). The SDK finds the corresponding configuration file based on the provided version.
Operation methods like putObject() all accept a single argument, an associative array that represents the parameters of the operation. The structure of this array (and the structure of the result object) is defined for each operation in the SDK’s API Documentation (e.g., see the API docs for putObject operation).
HTTP Handler Options
You can also fine-tune how the underlying HTTP handler executes the request by using the special
@http parameter. The options you can include in the @http parameter are the same as the ones you can set when you instantiate the client with the “http” client option (p. 29).
// Send the request through a proxy
$result = $s3Client->putObject([
'Bucket' => 'my-bucket', 'Key' => 'my-key',
'Body' => 'this is the body!', '@http' => [
'proxy' => 'http://192.168.16.1:10' ]
]);
Asynchronous Requests
You can send commands concurrently using the asynchronous features of the SDK. You can send requests asynchronously by suffixing an operation name with Async. This initiates the request and returns a promise. The promise is fulfilled with the result object on success or rejected with an exception on failure. This enables you to create multiple promises and have them send HTTP requests concurrently when the underlying HTTP handler transfers the requests.
Imports
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
Sample Code
// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk([
'region' => 'us-west-2', 'version' => 'latest' ]);
// Use an Aws\Sdk class to create the S3Client object.
$s3Client = $sdk->createS3();
//Listing all S3 Bucket
$CompleteSynchronously = $s3Client->listBucketsAsync();
// Block until the result is ready.
$CompleteSynchronously = $CompleteSynchronously->wait();
You can force a promise to complete synchronously by using the wait method of the promise. Forcing the promise to complete also “unwraps” the state of the promise by default, meaning it will either
Working with Result Objects
return the result of the promise or throw the exception that was encountered. When calling wait() on a promise, the process blocks until the HTTP request is completed and the result is populated or an exception is thrown.
When using the SDK with an event loop library, don’t block on results. Instead, use the then() method of a result to access a promise that is resolved or rejected when the operation completes.
Imports
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
Sample Code
// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk([
'region' => 'us-west-2', 'version' => 'latest'
]);// Use an Aws\Sdk class to create the S3Client object.
$s3Client = $sdk->createS3();
$promise = $s3Client->listBucketsAsync();
$promise
->then(function ($result) {
echo 'Got a result: ' . var_export($result, true);
})
->otherwise(function ($reason) {
echo 'Encountered an error: ' . $reason->getMessage();
});
}
Working with Result Objects
Executing a successful operation returns an Aws\Result object. Instead of returning the raw XML or JSON data of a service, the SDK coerces the response data into an associative array structure. It normalizes some aspects of the data based on its knowledge of the specific service and the underlying response structure.
You can access data from the AWSResult object like an associative PHP array.
Imports
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
Sample Code
// Use the us-east-2 region and latest version of each client.
$sharedConfig = [
'profile' => 'default', 'region' => 'us-east-2', 'version' => 'latest' ];
// Create an SDK class used to share configuration across clients.
Handling Errors
$sdk = new Aws\Sdk($sharedConfig);
// Use an Aws\Sdk class to create the S3Client object.
$s3 = $sdk->createS3();
$result = $s3->listBuckets();
foreach ($result['Buckets'] as $bucket) { echo $bucket['Name'] . "\n";
}
// Convert the result object to a PHP array
$array = $result->toArray();
The contents of the result object depend on the operation that was executed and the version of a service. The result structure of each API operation is documented in the API docs for each operation.
The SDK is integrated with JMESPath, a DSL used to search and manipulate JSON data or, in our case, PHP arrays. The result object contains a search() method you can use to more declaratively extract data from the result.
Sample Code
$s3 = $sdk->createS3();
$result = $s3->listBuckets();
$names = $result->search('Buckets[].Name');
Handling Errors
Synchronous Error Handling
If an error occurs while performing an operation, an exception is thrown. For this reason, if you need to handle errors in your code, use try/catch blocks around your operations. The SDK throws service- specific exceptions when an error occurs.
The following example uses the Aws\S3\S3Client. If there is an error, the exception thrown will be of the type Aws\S3\Exception\S3Exception. All service-specific exceptions that the SDK throws extend from the Aws\Exception\AwsException class. This class contains useful information about the failure, including the request-id, error code, and error type. Note for some services which support it, response data is coerced into an associative array structure (similar to Aws\Result objects), which can be accessed like a normal PHP associative array. The toArray() method will return any such data, if it exists.
Imports
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Aws\S3\Exception\S3Exception;
Sample Code
// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk([
'region' => 'us-west-2', 'version' => 'latest'
Handling Errors
]);
// Use an Aws\Sdk class to create the S3Client object.
$s3Client = $sdk->createS3();
try {
$s3Client->createBucket(['Bucket' => 'my-bucket']);
} catch (S3Exception $e) {
// Catch an S3 specific exception.
echo $e->getMessage();
} catch (AwsException $e) {
// This catches the more generic AwsException. You can grab information // from the exception using methods of the exception object.
echo $e->getAwsRequestId() . "\n";
echo $e->getAwsErrorType() . "\n";
echo $e->getAwsErrorCode() . "\n";
// This dumps any modeled response data, if supported by the service // Specific members can be accessed directly (e.g. $e['MemberName']) var_dump($e->toArray());
}
Asynchronous Error Handling
Exceptions are not thrown when sending asynchronous requests. Instead, you must use the then() or otherwise() method of the returned promise to receive the result or error.
Imports
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Aws\S3\Exception\S3Exception;
Sample Code
//Asynchronous Error Handling
$promise = $s3Client->createBucketAsync(['Bucket' => 'my-bucket']);
$promise->otherwise(function ($reason) { var_dump($reason);
});
// This does the same thing as the "otherwise" function.
$promise->then(null, function ($reason) { var_dump($reason);
});
You can “unwrap” the promise and cause the exception to be thrown instead.
Imports Imports
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
Upgrading from Version 2
use Aws\S3\Exception\S3Exception;
Sample Code
$promise = $s3Client->createBucketAsync(['Bucket' => 'my-bucket']);
//throw exception try {
$result = $promise->wait();
} catch (S3Exception $e) { echo $e->getMessage();
}
Upgrading from Version 2 of the AWS SDK for PHP
This topic shows how to migrate your code to use version 3 of the AWS SDK for PHP and how the new version differs from version 2 of the SDK.
NoteThe basic usage pattern of the SDK (i.e., $result = $client->operation($params);) has not changed from version 2 to version 3, which should result in a smooth migration.
Introduction
Version 3 of the AWS SDK for PHP represents a significant effort to improve the capabilities of the SDK, incorporate over two years of customer feedback, upgrade our dependencies, improve performance, and adopt the latest PHP standards.
What’s New in Version 3?
Version 3 of the AWS SDK for PHP follows the PSR-4 and PSR-7 standards and will follow the SemVer standard going forward.
Other new features include
• Middleware system for customizing service client behavior
• Flexible paginators for iterating through paginated results
• Ability to query data from result and paginator objects with JMESPath
• Easy debugging via the 'debug' configuration option
Decoupled HTTP layer
• Guzzle 6 is used by default to send requests, but Guzzle 5 is also supported.
• The SDK will work in environments where cURL is not available.
• Custom HTTP handlers are also supported.
Asynchronous requests
• Features like waiters and multipart uploaders can also be used asynchronously.
What’s Different from Version 2?
• Asynchronous workflows can be created using promises and coroutines.
• Performance of concurrent or batched requests is improved.
What’s Different from Version 2?
Project Dependencies are Updated
The dependencies of the SDK have changed in this version.
• The SDK now requires PHP 5.5+. We use generators liberally within the SDK code.
• We’ve upgraded the SDK to use Guzzle 6 (or 5), which provides the underlying HTTP client
implementation used by the SDK to send requests to the AWS services. The latest version of Guzzle brings with it a number of improvements, including asynchronous requests, swappable HTTP handlers, PSR-7 compliance, better performance, and more.
• The PSR-7 package from the PHP-FIG (psr/http-message) defines interfaces for representing HTTP requests, HTTP responses, URLs, and streams. These interfaces are used across the SDK and Guzzle, which provides interoperability with other PSR-7 compliant packages.
• Guzzle’s PSR-7 implementation (guzzlehttp/psr7) provides an implementation of the interfaces in PSR-7, and several helpful classes and functions. Both the SDK and Guzzle 6 rely on this package heavily.
• Guzzle’s Promises/A+ implementation (guzzlehttp/promises) is used throughout the SDK and Guzzle to provide interfaces for managing asynchronous requests and coroutines. While Guzzle’s multi-cURL HTTP handler ultimately implements the non-blocking I/O model that allows for asynchronous requests, this package provides the ability to program within that paradigm. See Promises in the AWS SDK for PHP Version 3 (p. 62) for more details.
• The PHP implementation of JMESPath (mtdowling/jmespath.php) is used in the SDK to provide the data querying ability of the Aws\Result::search() and Aws\ResultPaginator::search() methods. See JMESPath Expressions in the AWS SDK for PHP Version 3 (p. 82) for more details.
Region and Version Options Are Now Required
When instantiating a client for any service, specify the 'region' and 'version' options. In version 2 of the AWS SDK for PHP, 'version' was completely optional, and 'region' was sometimes optional.
In version 3, both are always required. Being explicit about both of these options allows you to lock into the API version and AWS Region you are coding against. When new API versions are created or new AWS Regions become available, you will be isolated from potentially breaking changes until you are ready to explicitly update your configuration.
NoteIf you’re not concerned about which API version you are using, you can just set the 'version' option to 'latest'. However, we recommend that you set the API version numbers explicitly for production code.
Not all services are available in all AWS Regions. You can find a list of available Regions using the Regions and Endpoints reference.
For services that are available only via a single, global endpoint (e.g., Amazon Route 53, AWS Identity and Access Management, and Amazon CloudFront), instantiate clients with their configured Region set to us-east-1.
Important
The SDK also includes multi-region clients, which can dispatch requests to different AWS Regions based on a parameter (@region) supplied as a command parameter. The Region used by default by these clients is specified with the region option supplied to the client constructor.
What’s Different from Version 2?
Client Instantiation Uses the Constructor
In version 3 of the AWS SDK for PHP, the way you instantiate a client has changed. Instead of the factory methods in version 2, you can simply instantiate a client by using the new keyword.
use Aws\DynamoDb\DynamoDbClient;
// Version 2 style
$client = DynamoDbClient::factory([
'region' => 'us-east-2' ]);
// Version 3 style
$client = new DynamoDbClient([
'region' => 'us-east-2', 'version' => '2012-08-10' ]);
Note
Instantiating a client using the factory() method still works. However, it’s considered deprecated.
Client Configuration Has Changed
The client configuration options in version 3 of the AWS SDK for PHP have changed a little from version 2. See the Configuration for the AWS SDK for PHP Version 3 (p. 22) page for a description of all
supported options.
Important
In version 3, 'key' and 'secret' are no longer valid options at the root level, but you can pass them in as part of the 'credentials' option. One reason we made this was to discourage developers from hard-coding their AWS credentials into their projects.
The Sdk Object
Version 3 of the AWS SDK for PHP introduces the Aws\Sdk object as a replacement to Aws\Common
\Aws. The Sdk object acts as a client factory and is used to manage shared configuration options across multiple clients.
Although the Aws class in version 2 of the SDK worked like a service locator (it always returned the same instance of a client), the Sdk class in version 3 returns a new instance of a client every time it’s used.
The Sdk object also doesn’t support the same configuration file format from version 2 of the SDK. That configuration format was specific to Guzzle 3 and is now obsolete. Configuration can be done more simply with basic arrays, and is documented in Using the Sdk Class (p. 7).
Some API Results Have Changed
To provide consistency in how the SDK parses the result of an API operation, Amazon ElastiCache, Amazon RDS, and Amazon Redshift now have an additional wrapping element on some API responses.
For example, calling the Amazon RDSDescribeEngineDefaultParameters result in version 3 now includes a wrapping “EngineDefaults” element. In version 2, this element was not present.
$client = new Aws\Rds\RdsClient([
'region' => 'us-west-1', 'version' => '2014-09-01'
What’s Different from Version 2?
]);
// Version 2
$result = $client->describeEngineDefaultParameters();
$family = $result['DBParameterGroupFamily'];
$marker = $result['Marker'];
// Version 3
$result = $client->describeEngineDefaultParameters();
$family = $result['EngineDefaults']['DBParameterGroupFamily'];
$marker = $result['EngineDefaults']['Marker'];
The following operations are affected and now contain a wrapping element in the output of the result (provided below in parentheses):
• Amazon ElastiCache
• AuthorizeCacheSecurityGroupIngress (CacheSecurityGroup)
• CopySnapshot (Snapshot)
• CreateCacheCluster (CacheCluster)
• CreateCacheParameterGroup (CacheParameterGroup)
• CreateCacheSecurityGroup (CacheSecurityGroup)
• CreateCacheSubnetGroup (CacheSubnetGroup)
• CreateReplicationGroup (ReplicationGroup)
• CreateSnapshot (Snapshot)
• DeleteCacheCluster (CacheCluster)
• DeleteReplicationGroup (ReplicationGroup)
• DeleteSnapshot (Snapshot)
• DescribeEngineDefaultParameters (EngineDefaults)
• ModifyCacheCluster (CacheCluster)
• ModifyCacheSubnetGroup (CacheSubnetGroup)
• ModifyReplicationGroup (ReplicationGroup)
• PurchaseReservedCacheNodesOffering (ReservedCacheNode)
• RebootCacheCluster (CacheCluster)
• RevokeCacheSecurityGroupIngress (CacheSecurityGroup)
• Amazon RDS
• AddSourceIdentifierToSubscription (EventSubscription)
• AuthorizeDBSecurityGroupIngress (DBSecurityGroup)
• CopyDBParameterGroup (DBParameterGroup)
• CopyDBSnapshot (DBSnapshot)
• CopyOptionGroup (OptionGroup)
• CreateDBInstance (DBInstance)
• CreateDBInstanceReadReplica (DBInstance)
• CreateDBParameterGroup (DBParameterGroup)
• CreateDBSecurityGroup (DBSecurityGroup)
• CreateDBSnapshot (DBSnapshot)
• CreateDBSubnetGroup (DBSubnetGroup)
• CreateEventSubscription (EventSubscription)
• CreateOptionGroup (OptionGroup)
• DeleteDBInstance (DBInstance)
• DeleteDBSnapshot (DBSnapshot)
What’s Different from Version 2?
• DeleteEventSubscription (EventSubscription)
• DescribeEngineDefaultParameters (EngineDefaults)
• ModifyDBInstance (DBInstance)
• ModifyDBSubnetGroup (DBSubnetGroup)
• ModifyEventSubscription (EventSubscription)
• ModifyOptionGroup (OptionGroup)
• PromoteReadReplica (DBInstance)
• PurchaseReservedDBInstancesOffering (ReservedDBInstance)
• RebootDBInstance (DBInstance)
• RemoveSourceIdentifierFromSubscription (EventSubscription)
• RestoreDBInstanceFromDBSnapshot (DBInstance)
• RestoreDBInstanceToPointInTime (DBInstance)
• RevokeDBSecurityGroupIngress (DBSecurityGroup)
• Amazon Redshift
• AuthorizeClusterSecurityGroupIngress (ClusterSecurityGroup)
• AuthorizeSnapshotAccess (Snapshot)
• CopyClusterSnapshot (Snapshot)
• CreateCluster (Cluster)
• CreateClusterParameterGroup (ClusterParameterGroup)
• CreateClusterSecurityGroup (ClusterSecurityGroup)
• CreateClusterSnapshot (Snapshot)
• CreateClusterSubnetGroup (ClusterSubnetGroup)
• CreateEventSubscription (EventSubscription)
• CreateHsmClientCertificate (HsmClientCertificate)
• CreateHsmConfiguration (HsmConfiguration)
• DeleteCluster (Cluster)
• DeleteClusterSnapshot (Snapshot)
• DescribeDefaultClusterParameters (DefaultClusterParameters)
• DisableSnapshotCopy (Cluster)
• EnableSnapshotCopy (Cluster)
• ModifyCluster (Cluster)
• ModifyClusterSubnetGroup (ClusterSubnetGroup)
• ModifyEventSubscription (EventSubscription)
• ModifySnapshotCopyRetentionPeriod (Cluster)
• PurchaseReservedNodeOffering (ReservedNode)
• RebootCluster (Cluster)
• RestoreFromClusterSnapshot (Cluster)
• RevokeClusterSecurityGroupIngress (ClusterSecurityGroup)
• RevokeSnapshotAccess (Snapshot)
• RotateEncryptionKey (Cluster)
Enum Classes Have Been Removed
What’s Different from Version 2?
versions, can change over time, can conflict with PHP reserved words, and ended up not being very useful, we have removed them in version 3. This supports the data-driven and API version agnostic nature of version 3.
Instead of using values from Enum objects, use the literal values directly (e.g., CannedAcl::PUBLIC_READ → 'public-read').
Fine-Grained Exception Classes Have Been Removed
We have removed the fine-grained exception classes that existed in each service’s namespaces (e.g., Aws
\Rds\Exception\{SpecificError}Exception) for very similar reasons that we removed Enums.
The exceptions thrown by a service or operation are dependent on which API version is used (they can change from version to version). Also, the complete list of the exceptions that can be thrown by a given operation is not available, which made version 2’s fine-grained exception classes incomplete.
Handle errors by catching the root exception class for each service (e.g., Aws\Rds\Exception
\RdsException). You can use the getAwsErrorCode() method of the exception to check for specific error codes. This is functionally equivalent to catching different exception classes, but provides that function without adding bloat to the SDK.
Static Facade Classes Have Been Removed
In version 2 of the AWS SDK for PHP, there was an obscure feature inspired by Laravel that allowed you to call enableFacades() on the Aws class to enable static access to the various service clients. This feature goes against PHP best practices, and we stopped documenting it over a year ago. In version 3, this feature is removed completely. Retrieve your client objects from the Aws\Sdk object and use them as object instances, not static classes.
Paginators Supersede iterators
Version 2 of the AWS SDK for PHP had a feature named * iterators*. These were objects that were used for iterating over paginated results. One complaint we had about these was that they were not flexible enough, because the iterator only emitted specific values from each result. If there were other values you needed from the results, you could only retrieve them via event listeners.
In version 3, iterators have been replaced with Paginators (p. 77). Their purpose is similar, but
paginators are more flexible. This is because they yield result objects instead of values from a response.
The following examples show how paginators are different from iterators, by demonstrating how to retrieve paginated results for the S3 ListObjects operation in both version 2 and version 3.
// Version 2
$objects = $s3Client->getIterator('ListObjects', ['Bucket' => 'my-bucket']);
foreach ($objects as $object) { echo $object['Key'] . "\n";
}
// Version 3
$results = $s3Client->getPaginator('ListObjects', ['Bucket' => 'my-bucket']);
foreach ($results as $result) {
// You can extract any data that you want from the result.
foreach ($result['Contents'] as $object) { echo $object['Key'] . "\n";
} }
Paginator objects have a search() method that enables you to use JMESPath (p. 82) expressions to extract data more easily from the result set.
Comparing Code Samples from Both Versions of the SDK
$results = $s3Client->getPaginator('ListObjects', ['Bucket' => 'my-bucket']);
foreach ($results->search('Contents[].Key') as $key) { echo $key . "\n";
}
NoteThe getIterator() method is still supported to allow for a smooth transition to version 3, but we encourage you to migrate your code to use paginators.
Many Higher-Level Abstractions Have Changed
In general, many of the higher-level abstractions (service-specific helper objects, aside from the clients) have been improved or updated. Some have even been removed.
• Updated:
• The way you use Amazon S3 Multipart Upload (p. 214) has changed. Amazon S3 Glacier Multipart Upload has been changed in similar ways.
• The way to create Amazon S3 pre-signed URLs (p. 222) has changed.
• The Aws\S3\Sync namespace has been replaced by the Aws\S3\Transfer class. The S3Client::uploadDirectory() and S3Client::downloadBucket() methods are still available, but have different options. See the documentation for Amazon S3 Transfer Manager with AWS SDK for PHP Version 3 (p. 98).
• Aws\S3\Model\ClearBucket and Aws\S3\Model\DeleteObjectsBatch have been replaced by Aws\S3\BatchDelete and S3Client::deleteMatchingObjects().
• The options and behaviors for the Using the DynamoDB Session Handler with AWS SDK for PHP Version 3 (p. 87) have changed slightly.
• The Aws\DynamoDb\Model\BatchRequest namespace has been replaced by Aws\DynamoDb
\WriteRequestBatch. See the documentation for DynamoDB WriteRequestBatch.
• The Aws\Ses\SesClient now handles base64 encoding the RawMessage when using SendRawEmail operation.
• Removed:
• Amazon DynamoDBItem, Attribute, and ItemIterator classes - These were previously deprecated in Version 2.7.0.
• Amazon SNS message validator - This is now a separate, lightweight project that does not require the SDK as a dependency. This project is, however, included in the Phar and ZIP distributions of the SDK. You can find a getting started guide on the AWS PHP Development blog.
• Amazon S3AcpBuilder and related objects were removed.
Comparing Code Samples from Both Versions of the SDK
The following examples show some of the ways in which using version 3 of the AWS SDK for PHP might differ from version 2.
Example: Amazon S3 ListObjects Operation
From Version 2 of the SDK
<?php
require '/path/to/vendor/autoload.php';
Comparing Code Samples from Both Versions of the SDK
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$s3 = S3Client::factory([
'profile' => 'my-credential-profile', 'region' => 'us-east-1'
]);
try {
$result = $s3->listObjects([
'Bucket' => 'my-bucket-name', 'Key' => 'my-object-key' ]);
foreach ($result['Contents'] as $object) { echo $object['Key'] . "\n";
}
} catch (S3Exception $e) { echo $e->getMessage() . "\n";
}
From Version 3 of the SDK
Key differences:
• Use new instead of factory() to instantiate the client.
• The 'version' and 'region' options are required during instantiation.
<?php
require '/path/to/vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$s3 = new S3Client([
'profile' => 'my-credential-profile', 'region' => 'us-east-1',
'version' => '2006-03-01' ]);
try {
$result = $s3->listObjects([
'Bucket' => 'my-bucket-name', 'Key' => 'my-object-key' ]);
foreach ($result['Contents'] as $object) { echo $object['Key'] . "\n";
}
} catch (S3Exception $e) { echo $e->getMessage() . "\n";
}
Example: Instantiating a Client with global Configuration
From Version 2 of the SDK
<?php return array(
Comparing Code Samples from Both Versions of the SDK
'includes' => array('_aws'), 'services' => array(
'default_settings' => array(
'params' => array(
'profile' => 'my_profile', 'region' => 'us-east-1' )
),
'dynamodb' => array(
'extends' => 'dynamodb', 'params' => array(
'region' => 'us-west-2' )
), ) );
<?php
require '/path/to/vendor/autoload.php';
use Aws\Common\Aws;
$aws = Aws::factory('path/to/my/config.php');
$sqs = $aws->get('sqs');
// Note: SQS client will be configured for us-east-1.
$dynamodb = $aws->get('dynamodb');
// Note: DynamoDB client will be configured for us-west-2.
From Version 3 of the SDK
Key differences:
• Use the Aws\Sdk class instead of Aws\Common\Aws.
• There’s no configuration file. Use an array for configuration instead.
• The 'version' option is required during instantiation.
• Use the create<Service>() methods instead of get('<service>').
<?php
require '/path/to/vendor/autoload.php';
$sdk = new Aws\Sdk([
'profile' => 'my_profile', 'region' => 'us-east-1', 'version' => 'latest', 'DynamoDb' => [
'region' => 'us-west-2', ],
]);
$sqs = $sdk->createSqs();
// Note: Amazon SQS client will be configured for us-east-1.
$dynamodb = $sdk->createDynamoDb();
// Note: DynamoDB client will be configured for us-west-2.
Configuration Options
Configuring the AWS SDK for PHP Version 3
The AWS SDK for PHP consists of various features and components. Each of the following topics describe the components that are used in the SDK.
Topics
• Configuration for the AWS SDK for PHP Version 3 (p. 22)
• Credentials for the AWS SDK for PHP Version 3 (p. 41)
• Command Objects in the AWS SDK for PHP Version 3 (p. 57)
• Promises in the AWS SDK for PHP Version 3 (p. 62)
• Handlers and Middleware in the AWS SDK for PHP Version 3 (p. 67)
• Streams in the AWS SDK for PHP Version 3 (p. 74)
• Paginators in the AWS SDK for PHP Version 3 (p. 77)
• Waiters in the AWS SDK for PHP Version 3 (p. 79)
• JMESPath Expressions in the AWS SDK for PHP Version 3 (p. 82)
Configuration for the AWS SDK for PHP Version 3
This guide describes client constructor options. These options can be provided in a client constructor or provided to the Aws\Sdk class. The array of options provided to a specific type of client can vary, based on which client you are creating. These custom client configuration options are described in the API documentation of each client.
Note that some configuration options will check and use default values based on environment variables or an AWS configuration file. By default, the configuration file being checked will be .aws/config in your home directory, commonly ~/.aws/config. However, you can use the environment variable AWS_CONFIG_FILE to set where your default config file location is. This may be especially useful if you are restricting file access to certain directories with open_basedir and the like.
Configuration Options
• api_provider (p. 23)
• credentials (p. 23)
• debug (p. 24)
• stats (p. 26)
• endpoint (p. 27)
• endpoint_provider (p. 27)
• endpoint_discovery (p. 28)
• handler (p. 29)
• http (p. 29)
• http_handler (p. 35)
api_provider
• profile (p. 36)
• region (p. 36)
• retries (p. 36)
• scheme (p. 38)
• service (p. 39)
• signature_provider (p. 39)
• signature_version (p. 39)
• ua_append (p. 40)
• use_aws_shared_config_files (p. 40)
• validate (p. 40)
• version (p. 41)
The following example shows how to pass options into an Amazon S3 client constructor.
use Aws\S3\S3Client;
$options = [
'region' => 'us-west-2', 'version' => '2006-03-01', 'signature_version' => 'v4'
];
$s3Client = new S3Client($options);
See the basic usage guide (p. 6) for more information about constructing clients.
api_provider
Type
callable
A PHP callable that accepts a type, service, and version argument, and returns an array of corresponding configuration data. The type value can be one of api, waiter, or paginator.
By default, the SDK uses an instance of Aws\Api\FileSystemApiProvider that loads API files from the src/data folder of the SDK.
credentials
Type
array|Aws\CacheInterface|Aws\Credentials\CredentialsInterface|bool|callable
Pass an Aws\Credentials\CredentialsInterface object to use a specific credentials instance.
$credentials = new Aws\Credentials\Credentials('key', 'secret');
$s3 = new Aws\S3\S3Client([
'version' => 'latest', 'region' => 'us-west-2', 'credentials' => $credentials
debug
]);
If you don’t provide a credentials option, the SDK attempts to load credentials from your environment in the following order:
1. Load credentials from environment variables (p. 43).
2. Load credentials from a credentials .ini file (p. 43).
3. Load credentials from an IAM role (p. 45).
Pass false to use null credentials and not sign requests.
$s3 = new Aws\S3\S3Client([
'version' => 'latest', 'region' => 'us-west-2', 'credentials' => false ]);
Pass a callable credential provider (p. 49) function to create credentials using a function.
use Aws\Credentials\CredentialProvider;
// Only load credentials from environment variables
$provider = CredentialProvider::env();
$s3 = new Aws\S3\S3Client([
'version' => 'latest', 'region' => 'us-west-2', 'credentials' => $provider ]);
Pass credentials cached to an instance of Aws\CacheInterface to cache the values returned by the default provider chain across multiple processes.
use Aws\Credentials\CredentialProvider;
use Aws\DoctrineCacheAdapter;
use Doctrine\Common\Cache\ApcuCache;
$cache = new DoctrineCacheAdapter(new ApcuCache);
$provider = CredentialProvider::defaultProvider();
$cachedProvider = CredentialProvider::cache($provider, $cache);
$s3 = new Aws\S3\S3Client([
'version' => 'latest', 'region' => 'us-west-2',
'credentials' => $cachedProvider ]);
You can find more information about providing credentials to a client in the Credentials for the AWS SDK for PHP Version 3 (p. 41) guide.
Note
Credentials are loaded and validated lazily when they are used.
debug
Type
bool|array
debug
Outputs debug information about each transfer. Debug information contains information about each state change of a transaction as it is prepared and sent over the wire. Also included in the debug output is information about the specific HTTP handler used by a client (e.g., debug cURL output).
Set to true to display debug information when sending requests.
$s3 = new Aws\S3\S3Client([
'version' => 'latest', 'region' => 'us-west-2', 'debug' => true
]);
// Perform an operation to see the debug output
$s3->listBuckets();
Alternatively, you can provide an associative array with the following keys.
logfn (callable)
Function that is invoked with log messages. By default, PHP’s echo function is used.
stream_size (int)
When the size of a stream is greater than this number, the stream data is not logged. Set to 0 to not log any stream data.
scrub_auth (bool)
Set to false to disable the scrubbing of auth data from the logged messages (meaning your AWS access key ID and signature will be passed through to the logfn).
http (bool)
Set to false to disable the “debug” feature of lower-level HTTP handlers (e.g., verbose cURL output).
auth_headers (array)
Set to a key-value mapping of headers you want to replace mapped to the value you want to replace them with. These values are not used unless scrub_auth is set to true.
auth_strings (array)
Set to a key-value mapping of regular expressions to map to their replacements. These values are used by the authentication data scrubber if scrub_auth is set to true.
$s3 = new Aws\S3\S3Client([
'version' => 'latest', 'region' => 'us-west-2', 'debug' => [
'logfn' => function ($msg) { echo $msg . "\n"; }, 'stream_size' => 0,
'scrub_auth' => true, 'http' => true, 'auth_headers' => [
'X-My-Secret-Header' => '[REDACTED]', ],
'auth_strings' => [
'/SuperSecret=[A-Za-z0-9]{20}/i' => 'SuperSecret=[REDACTED]', ],
] ]);
stats
// Perform an operation to see the debug output
$s3->listBuckets();
NoteThe debug output is extremely useful when diagnosing issues in the AWS SDK for PHP. Please provide the debug output for an isolated failure case when opening issues on the SDK.
stats
Type
bool|array
Binds transfer statistics to errors and results returned by SDK operations.
Set to true to gather transfer statistics on requests sent.
$s3 = new Aws\S3\S3Client([
'version' => 'latest', 'region' => 'us-west-2', 'stats' => true
]);
// Perform an operation
$result = $s3->listBuckets();
// Inspect the stats
$stats = $result['@metadata']['transferStats'];
Alternatively, you can provide an associative array with the following keys.
retries (bool)
Set to true to enable reporting on retries attempted. Retry statistics are collected by default and returned.
http (bool)
Set to true to enable collecting statistics from lower-level HTTP adapters (e.g., values returned in GuzzleHttpTransferStats). HTTP handlers must support an __on_transfer_stats option for this to have an effect. HTTP stats are returned as an indexed array of associative arrays; each associative array contains the transfer stats returned for a request by the client’s HTTP handler. Disabled by default.
If a request was retried, each request’s transfer stats are returned, with $result['@metadata']
['transferStats']['http'][0] containing the stats for the first request,
$result['@metadata']['transferStats']['http'][1] containing the statistics for the second request, and so on.
timer (bool)
Set to true to enable a command timer that reports the total wall clock time spent on an operation in seconds. Disabled by default.
$s3 = new Aws\S3\S3Client([
'version' => 'latest', 'region' => 'us-west-2',
endpoint
'stats' => [
'retries' => true, 'timer' => false, 'http' => true, ]
]);
// Perform an operation
$result = $s3->listBuckets();
// Inspect the HTTP transfer stats
$stats = $result['@metadata']['transferStats']['http'];
// Inspect the number of retries attempted
$stats = $result['@metadata']['transferStats']['retries_attempted'];
// Inspect the total backoff delay inserted between retries
$stats = $result['@metadata']['transferStats']['total_retry_delay'];
endpoint
Type string
The full URI of the web service. This is required for services, such as MediaConvert , that use account- specific endpoints. For these services, request this endpoint using the describeEndpoints method.
This is only required when connecting to a custom endpoint (e.g., a local version of Amazon S3 or Amazon DynamoDB Local).
Here’s an example of connecting to Amazon DynamoDB Local:
$client = new Aws\DynamoDb\DynamoDbClient([
'version' => '2012-08-10', 'region' => 'us-east-1'
'endpoint' => 'http://localhost:8000' ]);
See the AWS Regions and Endpoints for a list of available AWS Regions and endpoints.
endpoint_provider
Type
callable
An optional PHP callable that accepts a hash of options, including a “service” and “region” key. It returns NULL or a hash of endpoint data, of which the “endpoint” key is required.
Here’s an example of how to create a minimal endpoint provider.
$provider = function (array $params) { if ($params['service'] == 'foo') {
return ['endpoint' => $params['region'] . '.example.com'];
}
// Return null when the provider cannot handle the parameters return null;
});
endpoint_discovery
endpoint_discovery
Type
array|Aws\CacheInterface|Aws\EndpointDiscovery\ConfigurationInterface|
callable
Endpoint discovery identifies and connects to the correct endpoint for a service API that supports endpoint discovery. For services that support but don’t require endpoint discovery, enable
endpoint_discovery during client creation. If a service does not support endpoint discovery this configuration is ignored.
Aws\EndpointDiscovery\ConfigurationInterface
An optional configuration provider that enables automatic connection to the appropriate endpoint of a service API for operations the service specifies.
The Aws\EndpointDiscovery\Configuration object accepts two options, including a Boolean value, “enabled”, that indicates if endpoint discovery is enabled, and an integer “cache_limit” that indicates the maximum number of keys in the endpoint cache.
For each client created, pass an Aws\EndpointDiscovery\Configuration object to use a specific configuration for endpoint discovery.
use Aws\EndpointDiscovery\Configuration;
use Aws\S3\S3Client;
$enabled = true;
$cache_limit = 1000;
$config = new Aws\EndpointDiscovery\Configuration ( $enabled,
$cache_limit );
$s3 = new Aws\S3\S3Client([
'version' => 'latest', 'region' => 'us-east-2',
'endpoint_discovery' => $config, ]);
Pass an instance of Aws\CacheInterface to cache the values returned by endpoint discovery across multiple processes.
use Aws\DoctrineCacheAdapter;
use Aws\S3\S3Client;
use Doctrine\Common\Cache\ApcuCache;
$s3 = new S3Client([
'version' => 'latest', 'region' => 'us-west-2',
'endpoint_discovery' => new DoctrineCacheAdapter(new ApcuCache), ]);
Pass an array to endpoint discovery.
use Aws\S3\S3Client;
handler
$s3 = new S3Client([
'version' => 'latest', 'region' => 'us-west-2', 'endpoint_discovery' => [ 'enabled' => true, 'cache_limit' => 1000 ],
]);
handler
Type
callable
A handler that accepts a command object and request object, and that returns a promise (GuzzleHttp
\Promise\PromiseInterface) that is fulfilled with an Aws\ResultInterface object or rejected with an Aws\Exception\AwsException. A handler does not accept a next handler as it is terminal and expected to fulfill a command. If no handler is provided, a default Guzzle handler is used.
You can use the Aws\MockHandler to return mocked results or throw mock exceptions. You enqueue results or exceptions, and the MockHandler will dequeue them in FIFO order.
use Aws\Result;
use Aws\MockHandler;
use Aws\DynamoDb\DynamoDbClient;
use Aws\CommandInterface;
use Psr\Http\Message\RequestInterface;
use Aws\Exception\AwsException;
$mock = new MockHandler();
// Return a mocked result
$mock->append(new Result(['foo' => 'bar']));
// You can provide a function to invoke; here we throw a mock exception
$mock->append(function (CommandInterface $cmd, RequestInterface $req) { return new AwsException('Mock exception', $cmd);
});
// Create a client with the mock handler
$client = new DynamoDbClient([
'region' => 'us-west-2', 'version' => 'latest', 'handler' => $mock ]);
// Result object response will contain ['foo' => 'bar']
$result = $client->listTables();
// This will throw the exception that was enqueued
$client->listTables();
http
Type array
http
Set to an array of HTTP options that are applied to HTTP requests and transfers created by the SDK.
The SDK supports the following configuration options:
cert
Type
string|array
Specify the PEM formatted client side certificate.
• Set as a string for the path to only the certificate file.
use Aws\S3\S3Client;
$client = new S3Client([
'region' => 'us-west-2', 'version' => 'latest',
'http' => ['cert' => '/path/to/cert.pem']
]);
• Set as an array containing the path and password.
use Aws\S3\S3Client;
$client = new S3Client([
'region' => 'us-west-2', 'version' => 'latest', 'http' => [
'cert' => ['/path/to/cert.pem', 'password']
] ]);
connect_timeout
A float describing the number of seconds to wait while trying to connect to a server. Use 0 to wait indefinitely (the default behavior).
use Aws\DynamoDb\DynamoDbClient;
// Timeout after attempting to connect for 5 seconds
$client = new DynamoDbClient([
'region' => 'us-west-2', 'version' => 'latest', 'http' => [
'connect_timeout' => 5 ]
]);
debug
Type
bool|resource