Setting the AWS Region for the AWS SDK for PHP Version 3 - AWS SDK for PHP

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:

  1. 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' ]);
  2. Environment variables—If no Region is provided in code, the SDK checks for these environment variables in order:

    • AWS_REGION

    • AWS_DEFAULT_REGION

    # Example of setting Region through environment variables. export AWS_REGION=us-east-1
  3. AWS config files—If no Region environment variables are set, the SDK checks the AWS config files:

    1. The SDK looks in ~/.aws/config (or the location specified by AWS_CONFIG_FILE environment variable)

    2. The SDK examines the region setting within the profile specified by the AWS_PROFILE environment variable

    3. If no AWS_PROFILE is 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-1

    If the AWS_PROFILE environment variable is set with a value of "production", clients use the eu-central-1 Region. If no AWS_PROFILE environment variable exists, clients use the eu-west-1 Region.

  4. 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 config file and switching between them as needed.