GitHub|OSS SDK for PHP 2.0 Developer Guide|SDK Releases
Quick integration
Prerequisites
Requires PHP 7.4+. Download Composer for package management.
Run the php -version command to check the PHP version. If PHP is not installed or the version is earlier than 7.4, download and install PHP.
Install the SDK
-
Create a project directory and run the following command to install OSS SDK for PHP 2.0 via Composer. Use the latest version to ensure sample code compatibility.
mkdir oss-php-example && cd oss-php-example && composer require alibabacloud/oss-v2 -
Import the OSS SDK for PHP 2.0 package:
require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss;
Configure access credentials
Configure access credentials using a RAM user's AccessKey pair.
-
In the RAM console, create a RAM user with a permanent AccessKey Pair. Save the AccessKey pair and grant
AliyunOSSFullAccessto the RAM user. -
Use the AccessKey pair of the RAM user to configure environment variables.
Linux
-
Run the following commands to append the environment variable settings to the
~/.bashrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Run the following command to apply the changes.
source ~/.bashrc -
Run the following commands to check whether the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Run the following command in the terminal to view the default shell type.
echo $SHELL-
Perform the following steps based on the default shell type.
Zsh
-
Run the following commands to append the environment variable settings to the
~/.zshrcfile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Run the following command to apply the changes.
source ~/.zshrc -
Run the following commands to check whether the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to append the environment variable settings to the
~/.bash_profilefile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Run the following command to apply the changes.
source ~/.bash_profile -
Run the following commands to check whether the environment variables are configured.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
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"-
Run the following commands to check whether the environment variables are configured.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
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)-
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
Due to a policy change to improve compliance and security, starting March 20, 2025, new OSS users must use a custom domain name (CNAME) to perform data API operations on OSS buckets located in Chinese mainland regions. Default public endpoints are restricted for these operations. Refer to the official announcement for a complete list of the affected operations. If you access your data via HTTPS, you must bind a valid SSL Certificate to your custom domain. This is mandatory for OSS Console access, as the console enforces HTTPS.
Before you run the sample code, replace placeholders such as<region-id>with your actual region and endpoint, such asap-southeast-1.
<?php
/**
* Complete guide to 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.
* • You must specify an Alibaba Cloud region ID when initializing the client.
* • For a list of region IDs, see Regions and endpoints.
*
* ===========================================
* Endpoint configuration
* ===========================================
* • The SDK lets you customize the service endpoint by using the endpoint parameter.
* • If you omit the endpoint, the SDK automatically constructs a public endpoint from the region information.
* • For example, if the region is '<region-id>', the constructed endpoint is 'https://oss-<region-id>.aliyuncs.com'.
*
* ===========================================
* Protocol selection
* ===========================================
* • The SDK uses HTTPS by default to construct endpoints, which is the recommended protocol.
* • To use the HTTP protocol, include http:// in the endpoint.
* • HTTPS example: 'https://oss-<region-id>.aliyuncs.com'
* • HTTP example: 'http://oss-<region-id>.aliyuncs.com'
*/
// Import the autoloader to correctly load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// EnvironmentVariableCredentialsProvider reads 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.
$cfg->setRegion(region: "<region-id>");
// // Method 2: Specify both the region and the endpoint.
// $cfg->setRegion(region: '<region-id>')->setEndpoint(endpoint: 'https://oss-<region-id>.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
);
Expected output on successful upload:
status code: 200
request id: 687F2BEEDC44E0313527BA07
etag: "F0F18C2C66AE1DD512BDCD4366F76DA3"
Client configurations
Use a custom domain name
To enable browser file preview and CDN acceleration, bind a custom domain name to your bucket.
<?php
// Include the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Use EnvironmentVariableCredentialsProvider to obtain the AccessKey ID and AccessKey Secret from environment variables. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Load the default SDK configuration and set the credential provider. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Specify your custom domain name, such as www.example-***.com. // Note: setUseCname must be set to true to use a custom domain name. // Calling the PutCname operation requires PHP 8 or later. $cfg->setRegion('<region-id>')->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
// Load dependencies from the autoload file.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Read the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
# Load the default SDK configuration.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.
$cfg->setRegion(region: "<region-id>");
# Set the connection timeout.
$cfg->setConnectTimeout(connectTimeout: 30);
# Set the read/write timeout.
$cfg->setReadwriteTimeout(readwriteTimeout:30);
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Use the created client for subsequent operations...
Maximum retry attempts
The OSSClient retries failed requests 3 times by default.
For high-concurrency or unstable network scenarios, increase retries with setRetryMaxAttempts.
<?php
// Include 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 configuration and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);
$cfg->setRegion(region: "<region-id>");
// Set the maximum number of attempts 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 load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Create a credential provider that reads the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Load the default configuration and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);
$cfg->setRegion(region: "<region-id>");
// Disable SSL.
$cfg->setDisableSSL(true);
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Use the client for OSS 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 = '<region-id>'; // 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-<region-id>.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
// Include the autoload file to load dependencies correctly.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Create a credential provider that reads the AccessKey ID and AccessKey Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
# Load the default SDK config and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);
// Method 1: Specify the region and set setUseInternalEndpoint to true.
$cfg->setRegion('<region-id>')->setUseInternalEndpoint(true);
// // Method 2: Directly specify the region and endpoint.
// // Specify the internal endpoint for the region where the bucket is located.
// // To use the HTTP protocol, set the endpoint to 'http://oss-<region-id>-internal.aliyuncs.com'.
// $cfg->setRegion('<region-id>')->setEndpoint('https://oss-<region-id>-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
// Load project dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Read the AccessKey ID and AccessKey Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
# Load the default SDK configuration and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);
// Method 1: Specify the region and set setUseAccelerateEndpoint to true.
$cfg->setRegion('<region-id>')->setUseAccelerateEndpoint(true);
// // Method 2: Directly specify the region and endpoint.
// // Specify the regional acceleration endpoint.
// $cfg->setRegion('<region-id>')->setEndpoint('https://oss-accelerate.aliyuncs.com');
// Create an OSS client.
$client = new Oss\Client($cfg);
// Use this client for subsequent operations.
Use a private domain
<?php
// Import the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Create a credential provider that reads 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);
// Specify the region and set the endpoint to your private domain.
$cfg->setRegion('<region-id>')->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 Government 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
Select a credential method based on your authentication requirements.
Use the AccessKey pair of a RAM user
Initialize the credential provider with the AccessKey pair of an Alibaba Cloud account or a RAM user. Suitable for secure environments that require long-term OSS access without frequent credential rotation. This method requires manual AccessKey maintenance, which increases security risks.
-
An Alibaba Cloud account has full permissions on all resources. AccessKey pair leakage poses significant security risks. Use the AccessKey pair of a RAM user with 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
-
Use the AccessKey pair of a RAM user to configure environment variables.
Linux
-
Run the following commands on the CLI to add the configurations of the environment variables to the
~/.bashrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Apply the changes.
source ~/.bashrc -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Run the following command in the terminal to view the default shell type:
echo $SHELL-
Configure environment variables based on the default shell type.
Zsh
-
Run the following commands to add the configurations of the environment variables to the
~/.zshrcfile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Apply the changes.
source ~/.zshrc -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Run the following commands to add the configurations of the environment variables to the
~/.bash_profilefile:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Apply the changes.
source ~/.bash_profile -
Check whether the environment variables have taken effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
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)-
Check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
-
-
Restart your development environment (IDEs, terminals, backend services) after modifying environment variables to load the new values.
-
Use environment variables to pass the credential information.
<?php // Include the autoload file to ensure that dependencies are correctly loaded. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; $region = "<region-id>"; // 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 bucket's region. // 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.
Do not embed access credentials in applications in a production environment. This method is for testing purposes only.
<?php
// Include the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
$region = "<region-id>";
# Create a static credential provider and set your RAM user's AccessKey ID and AccessKey secret.
$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 bucket's region.
// 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.
-
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
-
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> -
-
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; $region = "<region-id>"; // Use EnvironmentVariableCredentialsProvider to read the AccessKey ID, AccessKey secret, and security token from environment variables. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use the default SDK configuration. $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.
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;
$region = "<region-id>";
# Specify your temporary AccessKey ID and AccessKey secret. Do not use the AccessKey pair of your Alibaba Cloud account.
# The AccessKey ID from STS starts with "STS.".
$stsAccessKeyId = 'STS.****************';
$stsAccessKeySecret = 'yourAccessKeySecret';
# Specify your security token.
$stsSecurityToken = 'yourSecurityToken';
# Create a static credential provider and explicitly set the temporary AccessKey ID, AccessKey secret, and security token.
$credentialsProvider = new Oss\Credentials\StaticCredentialsProvider($stsAccessKeyId, $stsAccessKeySecret, $stsSecurityToken);
// Use the default SDK configuration.
$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
For cross-account access or delegated authorization, initialize the credential provider with a RAM role ARN. The Credentials tool automatically obtains and refreshes STS tokens by calling AssumeRole. You can optionally assign a policy parameter to restrict the role's permissions.
-
An Alibaba Cloud account has full permissions on all resources. AccessKey pair leakage poses significant security risks. Use the AccessKey pair of a RAM user with 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.
-
Add the Alibaba Cloud credentials library credentials-php.
composer require alibabacloud/credentials -
Configure the AccessKey pair and RAM role ARN as access credentials.
<?php // Include the autoload file to ensure that dependencies are loaded correctly. 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, used to identify the session. 'roleSessionName' => 'yourRoleSessionName', // Optional. The policy used to limit the permissions of the STS token. 'policy' => 'Policy', ]); // Initialize a credential instance with the configuration object. $credential = new Credential($config); // Load the default SDK configuration. $cfg = Oss\Config::loadDefault(); // Set the credential provider to dynamically generate credentials with 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 containing the AccessKey ID, AccessKey secret, and security token. return new Oss\Credentials\Credentials( accessKeyId: $cred->getAccessKeyId(), // The temporary AccessKey ID. accessKeySecret: $cred->getAccessKeySecret(), // The temporary AccessKey secret. securityToken: $cred->getSecurityToken() // The security token (STS token). ); })); $region = '<region-id>'; $cfg->setRegion($region); // Create an OSS client instance. $client = new Oss\Client($cfg); // Use the client for subsequent operations...
Use an instance RAM role
For applications on ECS instances, ECI instances, or Container Service for Kubernetes worker nodes, use an instance RAM role. This method automatically refreshes STS tokens within your Container Service for Kubernetes instance without requiring an AccessKey pair. CreateRole.
-
Add the Alibaba Cloud credentials library credentials-php.
composer require alibabacloud/credentials -
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 for the credential type. $config = new Credential\Config([ // Set the credential type. For an instance RAM role, this value must be 'ecs_ram_role'. 'type' => 'ecs_ram_role', // The name of the RAM role attached to the instance. 'roleName' => "<role_name>", // Replace with your actual RAM role name. ]); // Initialize the credential instance. $credential = new Credential($config); // Load the default OSS configuration. $cfg = Oss\Config::loadDefault(); // Set the credential provider to a function that dynamically generates credentials. $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) { // Get the temporary STS token. $cred = $credential->getCredential(); // Return a new credential object with the AccessKey ID, AccessKey secret, and security token. return new Oss\Credentials\Credentials( accessKeyId: $cred->getAccessKeyId(), // Temporary AccessKey ID accessKeySecret: $cred->getAccessKeySecret(), // Temporary AccessKey secret securityToken: $cred->getSecurityToken() // Security token ); })); $region = '<region-id>'; $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
For untrusted applications in Container Service for Kubernetes (ACK) pods that should not access the worker node's instance RAM role, use RAM Roles for Service Account (RRSA). ACK mounts an OIDC token file per pod and injects configuration into environment variables. The Credentials tool reads these variables and calls AssumeRoleWithOIDC to obtain an STS token with minimal permissions. No AccessKey pair required. Use RRSA to configure RAM permissions for a ServiceAccount and isolate pod permissions.
-
Add the Alibaba Cloud credentials library credentials-php.
composer require alibabacloud/credentials
-
Configure the OIDC role ARN as the access credential.
<?php // Load dependencies from the autoload file. 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 also set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. 'oidcProviderArn' => '<oidc_provider_arn>', // Replace with the actual OIDC identity provider ARN. // Specify the OIDC token file path. You can also 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 also 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 also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. 'roleSessionName' => '<role_session_name>', // Replace with the actual role session name. // Optional: Specify a permission policy to further restrict the RAM role's 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 a credential provider that uses a callback function to dynamically generate credentials. $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) { // Obtain the temporary credential (STS token). $cred = $credential->getCredential(); // Return a credential object that contains the AccessKey ID, AccessKey secret, and security token. return new Oss\Credentials\Credentials( accessKeyId: $cred->getAccessKeyId(), // The temporary AccessKey ID. accessKeySecret: $cred->getAccessKeySecret(), // The temporary AccessKey secret. securityToken: $cred->getSecurityToken() // The security token (STS token). ); })); $region = '<region-id>'; $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.
-
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 a credential by using an anonymous function. $provider = new Oss\Credentials\CredentialsProviderFunc( function () { // Return a long-term credential, which contains 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 a temporary credential, which includes a security token, uncomment the following code and replace the values. /* return new Credentials( accessKeyId: 'id', // Replace with the actual STS temporary credential AccessKey ID. accessKeySecret: 'secret', // Replace with the actual STS temporary credential AccessKey secret. securityToken: 'token' // Replace with the actual STS security token. ); */ } ); // Load the default configuration and get the OSS configuration object. $cfg = Oss\Config::loadDefault(); // Set the credential provider to the dynamically generated provider. $cfg->setCredentialsProvider($provider); $region = '<region-id>'; $cfg->setRegion($region); // Create an OSS client instance. $client = new Oss\Client($cfg); // Use the created client for subsequent operations... -
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 { /** * Gets the credential object. * * @return Credentials Returns a credential object. */ public function getCredentials(): Credentials { // Return a long-term credential, which contains 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 a temporary credential, which includes a security token, uncomment the following code and replace the values. /* return new Credentials( accessKeyId: 'id', // Replace with the actual STS temporary credential AccessKey ID. accessKeySecret: 'secret', // Replace with the actual STS temporary credential AccessKey secret. securityToken: 'token' // Replace with the actual STS security token. ); */ } } // Instantiate the custom credential provider. $provider = new CustomerCredentialsProvider(); // Load the default configuration and get the OSS configuration object. $cfg = Oss\Config::loadDefault(); // Set the credential provider to the custom provider instance. $cfg->setCredentialsProvider($provider); $region = '<region-id>'; $cfg->setRegion($region); // Create an OSS client instance. $client = new Oss\Client($cfg); // Use the created client for subsequent operations...
Troubleshoot errors
When an error occurs, OSS returns an HTTP status code, message, request ID, and error code (EC). Use the EC to diagnose the issue.
-
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. ); -
Example error response. The 'EC': '0026-00000001' identifies the specific error cause.
teyimui@xxx 2051 get_object % php get_object_to_file.php region cn-hangzhou bucket xxx PHP Fatal error: Uncaught AlibabaCloud\Oss\V2\Exception\ServiceException: Error returned by Service. Http Status Code: 404 Error Code: NoSuchKey Request Id: 687F3B562C1E9331312B1F00 Message: The specified key does not exist. EC: 0026-00000001 Timestamp: Tue, 22 Jul 2025 07:18:46 GMT Request Endpoint: GET https://xxx.oss-cn-hangzhou.aliyuncs.com/put-php.txt in xxx -
Diagnose the error using the EC from the response:
-
Open the OpenAPI Troubleshooting Center.
-
In the search box, enter the EC, for example, 0026-00000001. Click Diagnose.
-
The results page shows the problem description, cause, and solution.
-
Sample code
The following table lists sample code for common operations.
|
Sample content |
GitHub sample file |
|
Set object tags (OSS SDK for PHP 2.0) |
|