All Products
Search
Document Center

Object Storage Service:OSS SDK for PHP 2.0

Last Updated:Dec 17, 2025

GitHubOSS SDK for PHP 2.0 Developer GuideSDK Releases

Quick integration

To integrate OSS SDK for PHP 2.0, follow these steps:

image

Prerequisites

PHP 7.4 or later is required. For more information, visit the official composer website to download the Composer package management tool.

You can run the php -version command to view the PHP version. If PHP is not installed or the version is earlier than 7.4, you can download and install PHP.

Install the SDK

  1. Create a project directory. Then, run the following command to use Composer to obtain OSS SDK for PHP 2.0. Select an OSS SDK for PHP 2.0 version based on your requirements. We recommend that you use the latest version to ensure that the sample code in this topic runs as expected.

    mkdir oss-php-example && cd oss-php-example && composer require alibabacloud/oss-v2
  2. Use the following code to import the OSS SDK for PHP 2.0 package.

    require_once __DIR__ . '/../vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;

Configure access credentials

Use the AccessKey pair of a RAM user to configure access credentials.

  1. In the RAM console, create a RAM user that uses a permanent AccessKey Pair for access. Save the AccessKey pair and grant the AliyunOSSFullAccess permission to the RAM user.

  2. Use the AccessKey pair of the RAM user to configure environment variables.

    Linux

    1. Run the following commands to append the environment variable settings to the ~/.bashrc file.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Run the following command to apply the changes.

        source ~/.bashrc
      2. Run the following commands to check whether the environment variables are configured.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Run the following command in the terminal to view the default shell type.

      echo $SHELL
      1. Perform the following steps based on the default shell type.

        Zsh

        1. Run the following commands to append the environment variable settings to the ~/.zshrc file.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Run the following command to apply the changes.

          source ~/.zshrc
        3. Run the following commands to check whether the environment variables are configured.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Run the following commands to append the environment variable settings to the ~/.bash_profile file.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        2. Run the following command to apply the changes.

          source ~/.bash_profile
        3. Run the following commands to check whether the environment variables are configured.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Run the following commands in the Command Prompt window.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Run the following commands to check whether the environment variables are configured.

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Run the following commands in PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      1. Run the following commands to check whether the environment variables are configured.

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Initialize the client

Initialize the OSSClient by specifying the region and endpoint. Then, run the test code.

<?php

/**
 * Complete guide for OSS SDK for PHP 2.0 client configuration
 *
 * ===========================================
 * V4 signature and region configuration
 * ===========================================
 * • OSS SDK for PHP 2.0 uses the V4 signature algorithm by default.
 * • When you initialize the client, you must specify an Alibaba Cloud region ID to identify the request region.
 * • This example uses the China (Hangzhou) region ID: cn-hangzhou. For other region IDs, see Regions and endpoints.
 *
 * ===========================================
 * Endpoint configuration
 * ===========================================
 * • OSS SDK for PHP 2.0 lets you customize the endpoint for service requests using the endpoint parameter.
 * • If you do not specify an endpoint, the SDK constructs a public endpoint based on the region information.
 * • For example, if the region is 'cn-hangzhou', the constructed endpoint is 'https://oss-cn-hangzhou.aliyuncs.com'.
 *
 * ===========================================
 * Protocol selection
 * ===========================================
 * • OSS SDK for PHP 2.0 uses the HTTPS protocol by default when it constructs endpoints. This is the recommended protocol.
 * • To use the HTTP protocol, explicitly specify http when you set the endpoint.
 * • HTTPS example: 'https://oss-cn-hangzhou.aliyuncs.com'
 * • HTTP example: 'http://oss-cn-hangzhou.aliyuncs.com'
 */

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);

// Method 1: Specify only the region (recommended). The SDK automatically constructs an HTTPS endpoint.
// China (Hangzhou): cn-hangzhou
$cfg->setRegion(region: "cn-hangzhou");

// // Method 2: Specify both the region and the endpoint.
// $cfg->setRegion(region: 'cn-hangzhou')->setEndpoint(endpoint: 'https://oss-cn-hangzhou.aliyuncs.com');

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// The data to upload.
$data = 'Hello OSS';

// Create a PutObjectRequest object to upload an object.
$request = new Oss\Models\PutObjectRequest(
                bucket: "Your Bucket Name",
                key: "Your Object Key",
            );
$request->body = Oss\Utils::streamFor($data); // Set the request body to a data stream.

// Perform the upload operation.
$result = $client->putObject($request);

// Print the upload result.
printf(
    'status code: %s' . PHP_EOL . // The HTTP status code.
    'request id: %s' . PHP_EOL .  // The request ID.
    'etag: %s' . PHP_EOL,         // The ETag of the object.
    $result->statusCode,
    $result->requestId,
    $result->etag
);

After you run the code, the following result is returned, which indicates that the file was uploaded.

status code: 200
request id: 687F2BEEDC44E0313527BA07
etag: "F0F18C2C66AE1DD512BDCD4366F76DA3"

Client configurations

What are the supported client configurations?

Parameter

Description

Example

region

(Required) The region where the request is sent.

setRegion("cn-hangzhou")

credentialsProvider

(Required) The access credential.

setCredentialsProvider(provider)

endpoint

The endpoint.

setEndpoint("oss-cn-hanghzou.aliyuncs.com")

retryMaxAttempts

The maximum number of retries for an HTTP request. The default value is 3.

setRetryMaxAttempts(5)

retryer

The retry implementation for an HTTP request.

setRetryer(customRetryer)

connectTimeout

The timeout period for establishing a connection. The default value is 10 seconds.

setConnectTimeout(5* time.Second)

readWriteTimeout

The timeout period for reading and writing data. The default value is 20 seconds.

setReadWriteTimeout(30 * time.Second)

insecureSkipVerify

Specifies whether to skip SSL certificate verification. By default, SSL certificates are verified.

setInsecureSkipVerify(true)

enabledRedirect

Specifies whether to enable HTTP redirection. By default, this feature is disabled.

setEnabledRedirect(true)

proxyHost

Set up a proxy server

setProxyHost(‘http://user:passswd@proxy.example-***.com’)

signatureVersion

The signature version. The default value is v4.

setSignatureVersion("v1")

disableSSL

Specifies whether to use HTTPS requests. By default, HTTPS is used.

setDisableSSL(true)

usePathStyle

Specifies whether to use path-style URLs. By default, virtual hosted-style URLs are used.

setUsePathStyle(true)

useCName

Specifies whether to use a custom domain name. By default, custom domain names are not used.

setUseCName(true)

useDualStackEndpoint

Specifies whether to use a dual-stack endpoint. By default, dual-stack endpoints are not used.

setUseDualStackEndpoint(true)

useAccelerateEndpoint

Specifies whether to use an acceleration endpoint. By default, acceleration endpoints are not used.

setUseAccelerateEndpoint(true)

useInternalEndpoint

Specifies whether to use an internal endpoint. By default, internal endpoints are not used.

setUseInternalEndpoint(true)

additionalHeaders

The additional request headers to be signed. This parameter is valid only for V4 signatures.

setAdditionalHeaders([‘content-length’])

userAgent

The additional User-Agent information.

setUserAgent(‘user identifier’)

Use a custom domain name

If you use the default OSS endpoint, you might encounter issues such as being unable to access or preview files. To resolve this, you can access OSS using a custom domain name. This method lets you preview files in a browser and use Alibaba Cloud CDN to accelerate content delivery.

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.

// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
// Specify your custom domain name, for example, www.example-***.com. Note that you must set setUseCname to true to enable the CNAME option. Otherwise, you cannot use the custom domain name.
// To call the PutCname operation, you must use PHP 8 or later.
$cfg->setRegion('cn-hangzhou')->setEndpoint('www.example-***.com')->setUseCname(true);

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Use the created client for subsequent operations.

Timeout control

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.

// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
$cfg->setRegion(region: "cn-hangzhou");

# Set the connection timeout period.
$cfg->setConnectTimeout(connectTimeout: 30);

# Set the timeout period for reading and writing data.
$cfg->setReadwriteTimeout(readwriteTimeout:30);

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Use the created client for subsequent operations.

Maximum retry attempts

If a request fails, the OSSClient retries the request three times by default.

In high-concurrency or unstable network scenarios, you can use setRetryMaxAttempts to increase the number of retries. This improves the request success rate.

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);

// China (Hangzhou): cn-hangzhou
$cfg->setRegion(region: "cn-hangzhou");

// Set the maximum number of retries for an HTTP request. The default value is 3.
$cfg->setRetryMaxAttempts(5);

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Use the created client for subsequent operations.

HTTP/HTTPS protocol

You can use setDisableSSL(true) to disable the HTTPS protocol.

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);

// China (Hangzhou): cn-hangzhou
$cfg->setRegion(region: "cn-hangzhou");

// Disable SSL.
$cfg->setDisableSSL(true);

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Use the created client for subsequent operations.

Use coroutines in the Swoole framework

The following code provides an example of how to create an OSS client that supports coroutines based on the Swoole framework.

<?php
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;
use GuzzleHttp\HandlerStack;
use Hyperf\Guzzle\CoroutineHandler;
use function Hyperf\Coroutine\co;

// Configure the OSS client.
$region = 'cn-hangzhou'; // The OSS region.
$bucket = 'bucket-name'; // The destination bucket.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Load credentials from environment variables.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.
$cfg->setRegion(region: $region); // Set the region.
$cfg->setEndpoint(endpoint: 'http://oss-cn-hangzhou.aliyuncs.com'); // Set the endpoint.

// Create an OSS client that supports coroutines.
$client = new Oss\Client(config: $cfg, options: ['handler' => HandlerStack::create(handler: new CoroutineHandler())]);

// Coroutine task 1: Upload swoole.txt.
co(function () use ($client, $bucket) {
    try {
        $key = 'swoole.txt'; // The object name.
        $data = 'Hello OSS'; // The object content.
        $request = new Oss\Models\PutObjectRequest($bucket, $key); // Create an upload request.
        $request->body = Oss\Utils::streamFor($data); // Set the request body.
        $result = $client->putObject(request: $request); // Perform the upload.
        echo "Task 1 Result:\n" . var_export($result, true) . "\n"; // Print the result.
    } catch (\Exception $e) {
        echo "Task 1 Error: " . $e->getMessage() . "\n"; // Catch the exception.
    }
});

// Coroutine task 2: Upload hyperf.txt.
co(function () use ($client, $bucket) {
    try {
        $key = 'hyperf.txt'; // The object name.
        $data = 'Hello OSS'; // The object content.
        $request = new Oss\Models\PutObjectRequest($bucket, $key); // Create an upload request.
        $request->body = Oss\Utils::streamFor($data); // Set the request body.
        $result = $client->putObject($request); // Perform the upload.
        echo "Task 2 Result:\n" . var_export($result, true) . "\n"; // Print the result.
    } catch (\Exception $e) {
        echo "Task 2 Error: " . $e->getMessage() . "\n"; // Catch the exception.
    }
});

Use an internal endpoint

If your application is deployed on an Alibaba Cloud ECS instance and needs to frequently access OSS resources in the same region, you can use an internal endpoint to reduce traffic costs and improve access speed.

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.

// Method 1: Specify the region and set setUseInternalEndpoint to true.
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
$cfg->setRegion('cn-hangzhou')->setUseInternalEndpoint(true);

// // Method 2: Directly specify the region and endpoint.
// // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
// // Specify the internal endpoint of the bucket's region. For example, for China (Hangzhou), set the endpoint to 'https://oss-cn-hangzhou-internal.aliyuncs.com'.
// // To use the HTTP protocol, set the endpoint to 'http://oss-cn-hangzhou-internal.aliyuncs.com'.
// $cfg->setRegion('cn-hangzhou')->setEndpoint('https://oss-cn-hanghzou-internal.aliyuncs.com');

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Use the created client for subsequent operations.

Use an acceleration endpoint

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.

// Method 1: Specify the region and set setUseAccelerateEndpoint to true.
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
$cfg->setRegion('cn-hangzhou')->setUseAccelerateEndpoint(true);

// // Method 2: Directly specify the region and endpoint.
// // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
// // Specify the acceleration endpoint of the bucket's region. For example, for China (Hangzhou), set the endpoint to 'https://oss-accelerate.aliyuncs.com'.
// $cfg->setRegion('cn-hangzhou')->setEndpoint('https://oss-accelerate.aliyuncs.com');

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Use the created client for subsequent operations.

Use a private domain

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.

// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
// Specify your private domain. Example: https://service.corp.example.com
$cfg->setRegion('cn-hangzhou')->setEndpoint('https://service.corp.example.com');

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Use the created client for subsequent operations.

Use an Alibaba Gov Cloud endpoint

The following code provides an example of how to configure the OSSClient using an Alibaba Gov Cloud endpoint.

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.

// Specify the region where the bucket is located. For example, for China (Beijing) Alibaba Gov Cloud 1, set the region to cn-north-2-gov-1.
// Specify the internal endpoint of the bucket's region. For example, for China (Beijing) Alibaba Gov Cloud 1, set the endpoint to 'https://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
// To use the HTTP protocol, set the endpoint to 'http://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
$cfg->setRegion('cn-north-2-gov-1')->setEndpoint('https://oss-cn-north-2-gov-1-internal.aliyuncs.com');

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Use the created client for subsequent operations.

Access credential configurations

OSS provides multiple methods to initialize credentials. You can select a method based on your authentication and authorization requirements.

How do I select access credentials?

Credential provider initialization method

Scenarios

Requires a pre-existing AccessKey pair or STS token

Underlying credential

Credential validity period

Credential rotation or refresh method

Use the AccessKey pair of a RAM user

Applications that are deployed in a secure and stable environment and are not susceptible to external attacks. These applications require long-term access to Alibaba Cloud services without frequent credential rotation.

Yes

AccessKey pair

Long-term

Manual rotation

Use an STS token

Applications that are deployed in an untrusted environment. You want to control the validity period and permissions for access.

Yes

STS token

Temporary

Manual refresh

Use a RAM role ARN

Applications that require authorized access to Alibaba Cloud services, such as cross-account access.

Yes

STS token

Temporary

Auto-refresh

Use an instance RAM role

Applications that are deployed on Alibaba Cloud ECS instances, ECI instances, or worker nodes of Container Service for Kubernetes.

No

STS token

Temporary

Auto-refresh

Use an OIDC role ARN

Untrusted applications that are deployed on worker nodes of Container Service for Kubernetes.

No

STS token

Temporary

Auto-refresh

Custom credential provider

If none of the preceding credential configuration methods meet your requirements, you can customize the method to obtain credentials.

Custom

Custom

Custom

Custom

Use the AccessKey pair of a RAM user

You can initialize the credential provider using the AccessKey pair (AccessKey ID and AccessKey secret) of an Alibaba Cloud account or a RAM user. This method is suitable if your application is deployed in a secure and stable environment, is not susceptible to external attacks, requires long-term access to OSS, and cannot frequently rotate credentials. Note that this method requires you to manually maintain an AccessKey pair, which increases security risks and maintenance complexity.

Warning
  • An Alibaba Cloud account has full permissions on all resources. The leakage of the AccessKey pair of an Alibaba Cloud account poses significant risks to your system. We recommend that you use the AccessKey pair of a RAM user that is granted the minimum required permissions.

  • For more information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when the AccessKey pair is created. You must save them immediately. If you forget the AccessKey pair, create a new one for rotation.

Environment variables

  1. Use the AccessKey pair of a RAM user to configure environment variables.

    Linux

    1. Run the following commands on the CLI to add the configurations of the environment variables to the ~/.bashrc file:

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Apply the changes.

        source ~/.bashrc
      2. Check whether the environment variables have taken effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Run the following command in the terminal to view the default shell type:

      echo $SHELL
      1. Configure environment variables based on the default shell type.

        Zsh

        1. Run the following commands to add the configurations of the environment variables to the ~/.zshrc file:

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Apply the changes.

          source ~/.zshrc
        3. Check whether the environment variables have taken effect:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Run the following commands to add the configurations of the environment variables to the ~/.bash_profile file:

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        2. Apply the changes.

          source ~/.bash_profile
        3. Check whether the environment variables have taken effect:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Run the following commands in CMD:

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Check whether the environment variables take effect:

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Run the following commands in PowerShell:

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      1. Check whether the environment variable takes effect:

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. After you modify the system environment variables, you must restart or refresh your development environment to ensure that the latest system environment variables are loaded. This includes IDEs, command-line interfaces, other desktop applications, and backend services.

  3. Use environment variables to pass the credential information.

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once __DIR__ . '/../vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    
    # Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
    $region = "cn-hangzhou";
    
    // Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
    $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
    
    // Use the default SDK configurations.
    $cfg = Oss\Config::loadDefault();
    $cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
    $cfg->setRegion($region); // Set the region where the bucket is located.
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations.

Static credentials

The following sample code shows how to hard-code access credentials by explicitly setting the AccessKey pair to use.

Warning

Do not embed access credentials in applications in a production environment. This method is for testing purposes only.

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

# Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
$region = "cn-hangzhou";

# Create a static credential provider and explicitly set the AccessKey ID and AccessKey secret. Replace them with the AccessKey ID and AccessKey secret of your RAM user.
$credentialsProvider = new Oss\Credentials\StaticCredentialsProvider("RAM AccessKey ID","RAM AccessKey Secret");

// Use the default SDK configurations.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Use the created client for subsequent operations.

Use an STS token

If your application requires temporary access to OSS, you can initialize the credential provider using the temporary identity credentials (AccessKey ID, AccessKey secret, and Security Token Service (STS) token) obtained from STS. Note that this method requires you to manually maintain an STS token, which increases security risks and maintenance complexity. In addition, if you want to temporarily access OSS multiple times, you must manually refresh the STS token.

Important
  • To quickly obtain an STS token using OpenAPI, see AssumeRole.

  • To obtain an STS token using an SDK, see Use an STS token to access OSS.

  • Note that an STS token has an expiration time that is specified when the token is generated. After the token expires, it becomes invalid and cannot be used.

  • For a list of STS service endpoints, see Endpoints.

Environment variables

  1. Set environment variables using temporary identity credentials.

    Mac OS X/Linux/Unix

    Warning
    • Use the temporary identity credentials (AccessKey ID, AccessKey secret, and STS token) obtained from STS. Do not use the AccessKey pair of a RAM user.

    • Note that the AccessKey ID obtained from STS starts with "STS", for example, "STS.****************".

    export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

    Windows

    Warning
    • Use the temporary identity credentials (AccessKey ID, AccessKey secret, and STS token) obtained from STS. Do not use the AccessKey pair of a RAM user.

    • Note that the AccessKey ID obtained from STS starts with "STS", for example, "STS.****************".

    set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
  2. Pass the credential information using environment variables.

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once __DIR__ . '/../vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    
    # Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
    $region = "cn-hangzhou";
    
    // Use EnvironmentVariableCredentialsProvider to read the AccessKey ID, AccessKey secret, and STS token from environment variables.
    $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
    
    // Use the default SDK configurations.
    $cfg = Oss\Config::loadDefault();
    $cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
    $cfg->setRegion($region); // Set the region where the bucket is located.
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations.

Static credentials

You can hard-code credentials in your application by explicitly setting the temporary AccessKey pair to use.

Warning

Do not embed access credentials in applications in a production environment. This method is for testing purposes only.

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

# Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
$region = "cn-hangzhou";

# Specify the temporary AccessKey ID and AccessKey secret that you obtained. Do not use the AccessKey ID and AccessKey secret of your Alibaba Cloud account.
# Note that the AccessKey ID obtained from STS starts with STS, as shown in the following example.
$stsAccessKeyId = 'STS.****************';
$stsAccessKeySecret = 'yourAccessKeySecret';
# Specify the STS token that you obtained.
$stsSecurityToken = 'yourSecurityToken';

# Create a static credential provider and explicitly set the temporary AccessKey ID, AccessKey secret, and STS token.
$credentialsProvider = new Oss\Credentials\StaticCredentialsProvider($stsAccessKeyId, $stsAccessKeySecret, $stsSecurityToken);

// Use the default SDK configurations.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Use the created client for subsequent operations.

Use a RAM role ARN

If your application requires authorized access to OSS, such as for cross-account access, you can initialize the credential provider using a RAM role Alibaba Cloud Resource Name (ARN). This method uses an STS token. By specifying the ARN of a RAM role, the Credentials tool obtains an STS token from STS and calls the AssumeRole operation to request a new STS token before the current token expires. You can also assign a value to the policy parameter to grant the RAM role a smaller set of permissions.

Important
  • An Alibaba Cloud account has full permissions on all resources. The leakage of the AccessKey pair of an Alibaba Cloud account poses significant risks to your system. We recommend that you use the AccessKey pair of a RAM user that is granted the minimum required permissions.

  • For more information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when the AccessKey pair is created. You must save them immediately. If you forget the AccessKey pair, create a new one for rotation.

  • For more information about how to obtain a RAM role ARN, see CreateRole.

  1. Add the Alibaba Cloud credentials library credentials-php.

    composer require alibabacloud/credentials
  2. Configure the AccessKey pair and RAM role ARN as access credentials.

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once __DIR__ . '/../vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    use AlibabaCloud\Credentials\Credential;
    
    // Create a configuration object to define the credential type and related information.
    $config = new Credential\Config([
        // Specify the credential type. In this example, the RAM role ARN type is used.
        'type' => 'ram_role_arn',
    
        // The AccessKey ID of the Alibaba Cloud account.
        'accessKeyId' => 'AccessKeyId',
    
        // The AccessKey secret of the Alibaba Cloud account.
        'accessKeySecret' => 'AccessKeySecret',
    
        // The ARN of the RAM role. Example: acs:ram::USER_Id:role/ROLE_NAME.
        'roleArn' => 'RoleArn',
    
        // The role session name, which is used to identify the current session.
        'roleSessionName' => 'yourRoleSessionName',
    
        // Optional. The policy that is used to limit the permissions of the STS token.
        'policy' => 'Policy',
    ]);
    
    // Initialize a credential instance using the configuration object.
    $credential = new Credential($config);
    
    // Load the default SDK configurations.
    $cfg = Oss\Config::loadDefault();
    
    // Set the credential provider to dynamically generate credentials using a callback function.
    $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) {
        // Obtain the temporary credentials (STS token).
        $cred = $credential->getCredential();
    
        // Return a credential object that contains the AccessKey ID, AccessKey secret, and STS token.
        return new Oss\Credentials\Credentials(
            accessKeyId: $cred->getAccessKeyId(),       // The temporary AccessKey ID.
            accessKeySecret: $cred->getAccessKeySecret(),   // The temporary AccessKey secret.
            securityToken: $cred->getSecurityToken()      // The STS token.
        );
    }));
    
    // Set the region information for the OSS client. For example, for China (Hangzhou), set the region to cn-hangzhou.
    $region = 'cn-hangzhou';
    $cfg->setRegion($region);
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations.

Use an instance RAM role

If your application runs on an ECS instance, an ECI instance, or a worker node of Container Service for Kubernetes, we recommend that you use an instance RAM role to initialize the credential provider. The underlying logic of this method is based on Security Token Service (STS) tokens. An instance RAM role lets you associate a role with an ECS instance, an ECI instance, or a worker node of Container Service for Kubernetes to automatically refresh the STS token within the instance. This method does not require an AccessKey pair or an STS token, which eliminates the risks associated with manually managing these credentials. For more information about how to obtain an instance RAM role, see CreateRole.

  1. Add the Alibaba Cloud credentials library credentials-php.

    composer require alibabacloud/credentials
  2. Configure the instance RAM role as the access credential.

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once 'vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    use AlibabaCloud\Credentials\Credential;
    
    // Create a configuration object to define the credential type and related information.
    $config = new Credential\Config([
        // Specify the credential type. In this example, the ECS instance RAM role type is used. The value is fixed to ecs_ram_role.
        'type' => 'ecs_ram_role',
    
        // Specify the name of the RAM role that is attached to the ECS instance.
        'roleName' => "<role_name>",  // Replace with the actual RAM role name.
    ]);
    
    // Initialize a credential instance using the configuration object.
    $credential = new Credential($config);
    
    // Load the default configurations and obtain the OSS configuration object.
    $cfg = Oss\Config::loadDefault();
    
    // Set the credential provider to dynamically generate credentials using a callback function.
    $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) {
        // Obtain the temporary credentials (STS token).
        $cred = $credential->getCredential();
    
        // Return a credential object that contains the AccessKey ID, AccessKey secret, and STS token.
        return new Oss\Credentials\Credentials(
            accessKeyId: $cred->getAccessKeyId(),       // The temporary AccessKey ID.
            accessKeySecret: $cred->getAccessKeySecret(), // The temporary AccessKey secret.
            securityToken: $cred->getSecurityToken()   // The STS token.
        );
    }));
    
    // Set the region information for the OSS client. For example, for China (Hangzhou), set the region to cn-hangzhou.
    $region = 'cn-hangzhou';
    $cfg->setRegion($region);
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations.
    

Use an OIDC role ARN

After you assign a RAM role to a worker node in Container Service for Kubernetes (ACK), applications in pods on that node can obtain an STS token from the metadata service. This is similar to applications on an ECS instance. However, you might not want untrusted applications, such as those from your customers, to obtain the STS token of the worker node's instance RAM role. To secure your cloud resources while allowing these applications to obtain the STS tokens they need with minimal permissions, you can use the RAM Roles for Service Account (RRSA) feature. This method uses STS tokens. ACK creates and mounts an OpenID Connect (OIDC) token file for each application pod and injects configuration information into environment variables. The Credentials tool reads these variables and calls the STS AssumeRoleWithOIDC operation to obtain an STS token for the attached role. This method does not require you to provide an AccessKey pair or an STS token, which eliminates the risks of manual credential management. For more information, see Use RRSA to configure RAM permissions for a ServiceAccount and isolate pod permissions.

  1. Add the Alibaba Cloud credentials library credentials-php.

    composer require alibabacloud/credentials
  1. Configure the OIDC role ARN as the access credential.

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once 'vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    use AlibabaCloud\Credentials\Credential;
    
    
    // Create a configuration object to define the credential type and related information.
    $config = new Credential\Config([
        // Specify the credential type. In this example, the OIDC role ARN type is used.
        'type' => 'oidc_role_arn',
    
        // Specify the ARN of the OIDC identity provider. You can set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
        'oidcProviderArn' => '<oidc_provider_arn>',  // Replace with the actual OIDC provider ARN.
    
        // Specify the OIDC token file path. You can set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
        'oidcTokenFilePath' => '<oidc_token_file_path>',  // Replace with the actual OIDC token file path.
    
        // Specify the ARN of the RAM role. You can set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
        'roleArn' => '<role_arn>',  // Replace with the actual RAM role ARN.
    
        // Specify the role session name. You can set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        'roleSessionName' => '<role_session_name>',  // Replace with the actual role session name.
    
        // Optional. Specify the permission policy for the RAM role to limit its permissions.
        // Example policy: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        'policy' => '',  // To limit permissions, replace this with the actual policy JSON string.
    
        // Optional. Specify the session validity period in seconds. The default value is 3,600 seconds.
        'roleSessionExpiration' => 3600,  // To adjust the validity period, modify this value.
    ]);
    
    // Initialize a credential instance using the configuration object.
    $credential = new Credential($config);
    
    // Load the default configurations and obtain the OSS configuration object.
    $cfg = Oss\Config::loadDefault();
    
    // Set the credential provider to dynamically generate credentials using a callback function.
    $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) {
        // Obtain the temporary credentials (STS token).
        $cred = $credential->getCredential();
    
        // Return a credential object that contains the AccessKey ID, AccessKey secret, and STS token.
        return new Oss\Credentials\Credentials(
            accessKeyId: $cred->getAccessKeyId(),       // The temporary AccessKey ID.
            accessKeySecret: $cred->getAccessKeySecret(), // The temporary AccessKey secret.
            securityToken: $cred->getSecurityToken()   // The STS token.
        );
    }));
    
    // Set the region information for the OSS client. For example, for China (Hangzhou), set the region to cn-hangzhou.
    $region = 'cn-hangzhou';
    $cfg->setRegion($region);
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations.

Use custom access credentials

If the preceding credential configuration methods do not meet your requirements, you can customize the method to obtain credentials. The SDK supports multiple implementation methods.

  1. Use Oss\Credentials\CredentialsProviderFunc

    Oss\Credentials\CredentialsProviderFunc is a usability wrapper for Oss\Credentials\CredentialsProvider.

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once 'vendor/autoload.php';
    
    // Import the necessary namespaces.
    use AlibabaCloud\Oss\V2 as Oss;
    use AlibabaCloud\Oss\V2\Credentials\Credentials;
    
    // Create a credential provider that dynamically generates credentials using an anonymous function.
    $provider = new Oss\Credentials\CredentialsProviderFunc(
        function () {
            // Return long-term credentials, which contain only an AccessKey ID and an AccessKey secret.
            return new Credentials(
                accessKeyId: 'id',         // Replace with the actual RAM AccessKey ID.
                accessKeySecret: 'secret'  // Replace with the actual RAM AccessKey secret.
            );
    
            // To return temporary credentials, which include an STS token, you can uncomment the following code and replace the values with your actual values.
            /*
            return new Credentials(
                accessKeyId: 'id',          // Replace with the actual temporary AccessKey ID.
                accessKeySecret: 'secret', // Replace with the actual temporary AccessKey secret.
                securityToken: 'token'     // Replace with the actual STS token.
            );
            */
        }
    );
    
    // Load the default configurations and obtain the OSS configuration object.
    $cfg = Oss\Config::loadDefault();
    
    // Set the credential provider to the dynamically generated credential provider.
    $cfg->setCredentialsProvider($provider);
    
    // Set the region information for the OSS client. For example, for China (Hangzhou), set the region to cn-hangzhou.
    $region = 'cn-hangzhou';
    $cfg->setRegion($region);
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations.
    
  2. Implement Oss\Credentials\CredentialsProvider

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once 'vendor/autoload.php';
    
    // Import the necessary namespaces.
    use AlibabaCloud\Oss\V2 as Oss;
    use AlibabaCloud\Oss\V2\Credentials\Credentials;
    
    // Custom credential provider class that implements the CredentialsProvider interface.
    class CustomerCredentialsProvider implements Oss\Credentials\CredentialsProvider
    {
        /**
         * Method to get credentials. Returns long-term or temporary credentials.
         *
         * @return Credentials Returns a credential object that contains AccessKey pair information.
         */
        public function getCredentials(): Credentials
        {
            // Return long-term credentials, which contain only an AccessKey ID and an AccessKey secret.
            return new Credentials(
                accessKeyId: 'id',         // Replace with the actual RAM AccessKey ID.
                accessKeySecret: 'secret'  // Replace with the actual RAM AccessKey secret.
            );
    
            // To return temporary credentials, which include an STS token, you can uncomment the following code and replace the values with your actual values.
            /*
            return new Credentials(
                accessKeyId: 'id',          // Replace with the actual temporary AccessKey ID.
                accessKeySecret: 'secret', // Replace with the actual temporary AccessKey secret.
                securityToken: 'token'     // Replace with the actual STS token.
            );
            */
        }
    }
    
    // Instantiate the custom credential provider.
    $provider = new CustomerCredentialsProvider();
    
    // Load the default configurations and obtain the OSS configuration object.
    $cfg = Oss\Config::loadDefault();
    
    // Set the credential provider to the custom credential provider.
    $cfg->setCredentialsProvider($provider);
    
    // Set the region information for the OSS client. For example, for China (Hangzhou), set the region to cn-hangzhou.
    $region = 'cn-hangzhou';
    $cfg->setRegion($region);
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations.
    

Troubleshoot errors

When you use OSS SDK for PHP 2.0 to access OSS, OSS returns information such as the HTTP status code, message, request ID, and error code (EC) if an error occurs. The EC corresponds to a specific cause of the error. You can use the EC to troubleshoot the error.

  1. For example, you use the following code to download a file that does not exist.

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once __DIR__ . '/../vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    
    // Define the description for command-line arguments.
    $optsdesc = [
        "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located (required).
        "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint (optional).
        "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name (required).
        "key" => ['help' => 'The name of the object', 'required' => True], // The object name (required).
    ];
    
    // Convert the parameter descriptions to the long option format required by getopt.
    // A colon ":" after each parameter indicates that the parameter requires a value.
    $longopts = \array_map(function ($key) {
        return "$key:";
    }, array_keys($optsdesc));
    
    // Parse the command-line arguments.
    $options = getopt("", $longopts);
    
    // Verify that all required parameters are present.
    foreach ($optsdesc as $key => $value) {
        if ($value['required'] === True && empty($options[$key])) {
            $help = $value['help']; // Get the help information for the parameter.
            echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
            exit(1); // Exit the program if a required parameter is missing.
        }
    }
    
    // Extract values from the parsed parameters.
    $region = $options["region"]; // The region where the bucket is located.
    $bucket = $options["bucket"]; // The bucket name.
    $key = $options["key"];       // The object name.
    
    // Load credentials from environment variables.
    // Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
    $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
    
    // Use the default SDK configurations.
    $cfg = Oss\Config::loadDefault();
    $cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
    $cfg->setRegion($region); // Set the region where the bucket is located.
    if (isset($options["endpoint"])) {
        $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
    }
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Create a GetObjectRequest object to get the content of the specified object.
    $request = new Oss\Models\GetObjectRequest(bucket: $bucket, key: $key);
    
    // Perform the get object operation.
    $result = $client->getObject($request);
    
    // Define the local file path to save the content.
    $localFilePath = './test/file.txt'; // Replace with the actual file path.
    
    // Write the content to the local file.
    file_put_contents( $localFilePath, $result->body->getContents());
    
    // Print the result.
    // Output the HTTP status code, request ID, and object content.
    printf(
        'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
        'request id:' . $result->requestId . PHP_EOL  // The request ID, used for debugging or tracking requests.
    );
    
  2. The following sample response is returned. The response contains 'EC': '0026-00000001', which is the unique identifier for the cause of the error.

  3. Follow these steps to find the cause of the problem and the corresponding solution based on the EC returned in the preceding sample error request.

    1. Open the OpenAPI Troubleshooting Center.

    2. In the search box, enter the EC, for example, 0026-00000001.

    3. Find the cause of the problem and the corresponding solution in the search results.

Sample code

OSS SDK for PHP 2.0 provides a rich set of sample code for your reference.

Sample content

GitHub sample file

Create a bucket (OSS SDK for PHP 2.0)

PutBucket.php

List buckets (OSS SDK for PHP 2.0)

ListBuckets.php

Check if a bucket exists (OSS SDK for PHP 2.0)

IsBucketExist.php

Get the region of a bucket (OSS SDK for PHP 2.0)

GetBucketLocation.php

Get bucket information (OSS SDK for PHP 2.0)

GetBucketInfo.php

Get the storage capacity of a bucket (OSS SDK for PHP 2.0)

GetBucketStat.php

Delete a bucket (OSS SDK for PHP 2.0)

DeleteBucket.php

Bucket tagging (OSS SDK for PHP 2.0)

Pay-by-requester (OSS SDK for PHP 2.0)

Simple upload (OSS SDK for PHP 2.0)

PutObject.php

Append upload (OSS SDK for PHP 2.0)

AppendObject.php

Multipart upload (OSS SDK for PHP 2.0)

CompleteMultipartUpload.php

Form upload (OSS SDK for PHP 2.0)

PostObject.php

Upload an object using a signed URL (OSS SDK for PHP 2.0)

Presign.php

File upload manager (OSS SDK for PHP 2.0)

Uploader.php

Simple download (OSS SDK for PHP 2.0)

GetObject.php

Range download (OSS SDK for PHP 2.0)

GetObject.php

Download an object using a signed URL (OSS SDK for PHP 2.0)

Presign.php

File download manager (OSS SDK for PHP 2.0)

Downloader.php

Copy an object (OSS SDK for PHP 2.0)

CopyObject.php

Multipart copy (OSS SDK for PHP 2.0)

UploadPartCopy.php

File copy manager (OSS SDK for PHP 2.0)

Copier.php

Check if an object exists (OSS SDK for PHP 2.0)

IsObjectExist.php

List objects (OSS SDK for PHP 2.0)

ListObjectsV2.php

Delete objects (OSS SDK for PHP 2.0)

DeleteObject.php

Restore a file

RestoreObject.php

Manage object metadata (OSS SDK for PHP 2.0)

HeadObject.php

Convert object storage classes (OSS SDK for PHP 2.0)

CopyObject.php

Rename a file (OSS SDK for PHP 2.0)

CopyObject.php

Manage symbolic links (OSS SDK for PHP 2.0)

Set object tags (OSS SDK for PHP 2.0)

Get object tags (OSS SDK for PHP 2.0)

Delete object tags (OSS SDK for PHP 2.0)

Manage bucket ACLs (OSS SDK for PHP 2.0)

Manage object ACLs (OSS SDK for PHP 2.0)

Bucket policies (OSS SDK for PHP 2.0)

Manage versioning (OSS SDK for PHP 2.0)

Hotlink protection (OSS SDK for PHP 2.0)

Cross-origin resource sharing (OSS SDK for PHP 2.0)

Retention policies (OSS SDK for PHP 2.0)

Server-side encryption (OSS SDK for PHP 2.0)

Client-side encryption (OSS SDK for PHP 2.0)

EncryptionClient.php

Data replication (OSS SDK for PHP 2.0)

Access tracking (OSS SDK for PHP 2.0)

Lifecycle management (OSS SDK for PHP 2.0)

Static website hosting (OSS SDK for PHP 2.0)

Log storage (OSS SDK for PHP 2.0)

Real-time access of Archive objects (OSS SDK for PHP 2.0)

PutBucketArchiveDirectRead.php

Scalar search (OSS SDK for PHP 2.0)

Vector search (OSS SDK for PHP 2.0)

Bind a custom domain name (OSS SDK for PHP 2.0)

Transfer acceleration (OSS SDK for PHP 2.0)

Synchronous processing (OSS SDK for PHP 2.0)

ProcessObject.php

Asynchronous processing (OSS SDK for PHP 2.0)

AsyncProcessObject.php

Global Block Public Access (OSS SDK for PHP 2.0)

PutPublicAccessBlock.php

Bucket-level Block Public Access (OSS SDK for PHP 2.0)

PutBucketPublicAccessBlock.php