GitHub|OSS SDK for PHP 2.0 Developer Guide|SDK Releases
Quick integration
To integrate OSS SDK for PHP 2.0, follow these steps:
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
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-v2Use 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.
In the RAM console, create a RAM user that uses a permanent AccessKey Pair for access. Save the AccessKey pair and grant the
AliyunOSSFullAccesspermission to 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'" >> ~/.bashrcRun the following command to apply the changes.
source ~/.bashrcRun 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 $SHELLPerform 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'" >> ~/.zshrcRun the following command to apply the changes.
source ~/.zshrcRun 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_profileRun the following command to apply the changes.
source ~/.bash_profileRun 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
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
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.
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.
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
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'" >> ~/.bashrcApply the changes.
source ~/.bashrcCheck 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 $SHELLConfigure 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'" >> ~/.zshrcApply the changes.
source ~/.zshrcCheck 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_profileApply the changes.
source ~/.bash_profileCheck 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)
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.
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.
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.
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
WarningUse 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
WarningUse 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; # 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.
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.
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.
Add the Alibaba Cloud credentials library credentials-php.
composer require alibabacloud/credentialsConfigure 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.
Add the Alibaba Cloud credentials library credentials-php.
composer require alibabacloud/credentialsConfigure 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.
Add the Alibaba Cloud credentials library credentials-php.
composer require alibabacloud/credentials
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.
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.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.
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. );The following sample response is returned. The response contains 'EC': '0026-00000001', which is the unique identifier for the cause of the error.
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.
Open the OpenAPI Troubleshooting Center.
In the search box, enter the EC, for example, 0026-00000001.
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 |
Set object tags (OSS SDK for PHP 2.0) | |