Setting the AWS Region for the AWS SDK for PHP Version 3
SDK clients connect to an AWS service in a specific AWS Region that you specify when you create the client. This configuration allows your application to interact with AWS resources in that geographical area. When you create a service client without explicitly setting a Region, the SDK uses the default Region from your external configuration.
Region resolution chain
The AWS SDK for PHP Version 3 uses the following order to determine which Region a service client uses:
-
Region provided in code—If you explicitly set the Region in the client constructor options, this takes precedence over all other sources.
$s3Client = new Aws\S3\S3Client([ 'region' => 'us-west-2' ]); -
Environment variables—If no Region is provided in code, the SDK checks for these environment variables in order:
AWS_REGIONAWS_DEFAULT_REGION
# Example of setting Region through environment variables. export AWS_REGION=us-east-1 -
AWS config files—If no Region environment variables are set, the SDK checks the AWS config files:
-
The SDK looks in
~/.aws/config(or the location specified byAWS_CONFIG_FILEenvironment variable) -
The SDK examines the region setting within the profile specified by the
AWS_PROFILEenvironment variable -
If no
AWS_PROFILEis specified, the SDK uses the "default" profile
As an example, assume we have the following configuration file settings:
# Example ~/.aws/config file. [default] region = eu-west-1 [profile production] region = eu-central-1If the
AWS_PROFILEenvironment variable is set with a value of "production", clients use theeu-central-1 Region. If noAWS_PROFILEenvironment variable exists, clients use theeu-west-1Region. -
-
If the SDK finds no Region value in any of the above sources, it throws an exception since a Region value is a required setting for a service client.
Best practices
Consider the following best practices when working with Regions in the AWS SDK for PHP Version 3:
- Explicitly set the Region in production code
-
For production applications, we recommend explicitly setting the Region in your code rather than relying on environment variables or the
config. This makes your code more predictable and less dependent on external configuration. - Use environment variables for development and testing
-
For development and testing environments, using environment variables allows for more flexibility without changing code.
- Use profiles for multiple environments
-
If your application needs to work with multiple AWS environments, consider using different profiles in your AWS
configfile and switching between them as needed.