All Products
Search
Document Center

Object Storage Service:Initialize an OSSClient instance for OSS SDK for PHP

Last Updated:Jul 05, 2024

OSSClient is the PHP client of Object Storage Service (OSS). It is used to manage OSS resources, such as buckets and objects. To use OSS SDK for PHP to initiate a request, you must initialize an OSSClient instance and modify the default configuration items.

Create an OSSClient instance

(Recommended) Use the V4 signature algorithm

We recommend that you use the V4 signature algorithm which provides better security. If you use the V4 signature algorithm, include the region parameter. The region parameter must be an Alibaba Cloud Region ID. Example: cn-Hangzhou. You must also declare OssClient::OSS_SIGNATURE_VERSION_V4. OSS SDK for PHP 2.7.0 and later support the V4 signature algorithm.

The following sample code provides an example on how to create an OSSClient instance by using an OSS endpoint and sign the request by using the V4 signature algorithm. To create an OSSClient instance by using a custom domain name or access credentials obtained from Security Token Service (STS), you can refer to the following sample code and change the variables:

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

try {
    // Obtain access credentials from environment variables and save the credentials in the provider. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    $provider = new EnvironmentVariableCredentialsProvider();
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    $endpoint = "https://oss-cn-hangzhou.aliyuncs.com";    
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,        
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        // Specify the region of the endpoint. Example: cn-hangzhou. 
        "region" => "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
} catch (OssException $e) {
    printf($e->getMessage() . "\n");
    return;
}

(Not recommended) Use the V1 signature algorithm

Important

From December 1, 2024, the V1 signature algorithm of Object Storage Service (OSS) is no longer available to new customers with new UIDs. From June 1, 2025, OSS no longer updates and maintains the V1 signature algorithm, and the V1 signature algorithm is no longer available for new buckets. Upgrade V1 signatures to V4 signatures at the earliest opportunity to prevent impact on your business.

Create an OSSClient instance by using an OSS endpoint

The following sample code provides an example on how to create an OSSClient instance by using an OSS endpoint. For more information about the OSS endpoints of different regions, see Regions and endpoints.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.  
$provider = new EnvironmentVariableCredentialsProvider();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

try {
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
    );
    $ossClient = new OssClient($config);
} catch (OssException $e) {
    print $e->getMessage();
}
                    

Create an OSSClient instance by using a custom domain name

The following sample code provides an example on how to create an OSSClient instance by using a custom domain name. For more information, see Map a custom domain name to the default domain name of a bucket.

Important

The listBuckets method is unavailable when a custom domain name is used.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.  
$provider = new EnvironmentVariableCredentialsProvider();
// Specify the custom domain name. Example: http://example.com. 
$endpoint = "http://example.com";

try {
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "cname"	=> true
    );
    $ossClient = new OssClient($config);    
} catch (OssException $e) {
    print $e->getMessage();
}    
                

Create an OSSClient instance by using access credentials obtained from STS

The following sample code provides an example on how to create an OSSClient instance by using access credentials obtained from STS:

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
// Before you run the sample code, make sure that the access credentials are configured. The access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
$provider = new EnvironmentVariableCredentialsProvider();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

try {
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,        
    );
    $ossClient = new OssClient($config);
} catch (OssException $e) {
    print $e->getMessage();
}
                    
                    

Create an OSSClient instance by using EcsRamRole

You can access OSS from an Elastic Compute Service (ECS) instance by using a RAM role attached to the instance. You can attach a RAM role to an ECS instance to access OSS from the instance by using temporary access credentials that are obtained from STS. STS temporary access credentials are automatically generated and updated. Applications can obtain the STS temporary access credentials by using the instance metadata URL.

Important

Before you use EcsRamRole to create an OSSClient instance, run the following command to install OSS SDK for PHP by using Composer:

composer require alibabacloud/credentials

The following sample code provides an example on how to create an OSSClient instance by using EcsRamRole:

<?php

if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
  }
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
  require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\CredentialsProvider;
use AlibabaCloud\Credentials\Credential;
use OSS\Credentials\StaticCredentialsProvider;
use OSS\Core\OssException;
use OSS\OssClient;
class AlibabaCloudCredentialsWrapper implements CredentialsProvider{
    /**
     * @var \OSS\Credentials\Credentials
     */
    private $wrapper;
    public function __construct($wrapper){
        $this->wrapper = $wrapper;
    }
    public function getCredentials(){
        $ak = $this->wrapper->getAccessKeyId();
        $sk = $this->wrapper->getAccessKeySecret();
        $token = $this->wrapper->getSecurityToken();
        return new StaticCredentialsProvider($ak, $sk, $token);
    }
}
$ecsRamRole = new Credential(array(
    // Set the temporary access credential type to ecs_ram_role. 
    'type'      => 'ecs_ram_role',
    // Specify the role name. 
    'role_name' => 'EcsRamRoleOssTest',
));
$providerWarpper = new AlibabaCloudCredentialsWrapper($ecsRamRole);
$provider = $providerWarpper->getCredentials();
$config = array(
    'provider' => $provider,
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    'endpoint'=> 'https://oss-cn-hangzhou.aliyuncs.com'
);
try {
    $ossClient = new OssClient($config);
} catch (OssException $e) {
    print $e->getMessage();
}

Create an OSSClient instance by using STSAssumeRole

Important

Before you use STSAssumeRole to create an OSSClient instance, run the following command to install OSS SDK for PHP by using Composer:

composer require alibabacloud/credentials

The following sample code provides an example on how to create an OSSClient instance by using STSAssumeRole:

<?php

if (is_file(__DIR__ . '/../autoload.php')) {
 require_once __DIR__ . '/../autoload.php';
 }
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
 require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\CredentialsProvider;
use AlibabaCloud\Credentials\Credential;
use OSS\Credentials\StaticCredentialsProvider;
use OSS\Core\OssException;
use OSS\OssClient;
class AlibabaCloudCredentialsWrapper implements CredentialsProvider{
 /**
 * @var \OSS\Credentials\Credentials
 */
 private $wrapper;
 public function __construct($wrapper){
 $this->wrapper = $wrapper;
 }
 public function getCredentials(){
 $ak = $this->wrapper->getAccessKeyId();
 $sk = $this->wrapper->getAccessKeySecret();
 $token = $this->wrapper->getSecurityToken();
 return new StaticCredentialsProvider($ak, $sk, $token);
 }
}
$ramRoleArn = new Credential(array(
 // Set the credential type to ram_role_arn. 
 'type' => 'ram_role_arn',
 // Before you run the sample code, make sure that the YOUR_ACCESS_KEY_ID and YOUR_ACCESS_KEY_SECRET environment variables are configured by using the AccessKey pair of the RAM user. 
 'access_key_id' => getenv('YOUR_ACCESS_KEY_ID'),
 'access_key_secret' => getenv('YOUR_ACCESS_KEY_SECRET'),
 // Specify the Alibaba Cloud Resource Name (ARN) of the RAM role, which is the ID of the role to be assumed. Format: acs:ram::$accountID:role/$roleName. 
 'role_arn' => 'acs:ram::17464958********:role/ossststest',
 // Specify a custom session name for the role to distinguish different tokens. 
 'role_session_name' => 'yourRoleSessionName',
 // Specify a custom policy. 
 'policy' => '',
));
$providerWarpper = new AlibabaCloudCredentialsWrapper($ramRoleArn);
$provider = $providerWarpper->getCredentials();
$config = array(
 'provider' => $provider,
 // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
 'endpoint'=> 'https://oss-cn-hangzhou.aliyuncs.com'
);
try {
 $ossClient = new OssClient($config);
 var_dump($ossClient);
} catch (OssException $e) {
 print $e->getMessage();
}

Configure an OSSClient instance

You can use an OSSClient instance to configure parameters, such as the proxy, connection timeout, and maximum number of connections. The following table describes the parameters.

Parameter

Description

Method

timeout

The timeout period for data transmission at the Socket layer. Unit: seconds. Default value: 5184000.

$ossClient->setTimeout(60);

connectTimeout

The timeout period to establish a connection. Unit: seconds. Default value: 10.

$ossClient->setConnectTimeout(600);

maxRetries

The maximum number of retries when a request error occurs. Default value: 3.

$ossClient->setMaxTries(5);

useSSL

Specifies whether to enable SSL-based authentication. Valid values:

  • true

  • false (default)

$ossClient->setUseSSL(true);

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.  
$provider = new EnvironmentVariableCredentialsProvider();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

try {
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
    );
    $ossClient = new OssClient($config);
    // Specify a timeout period for establishing a connection. 
    $ossClient->setConnectTimeout(300);
    // Specify the maximum number of retries when a request error occurs. 
    $ossClient->setMaxTries(5);    
    // Specify the timeout period for data transmission at the socket layer. 
    $ossClient->setTimeout(30);
    // Specify whether to enable SSL-based authentication. 
    $ossClient->setUseSSL(true);
} catch (OssException $e) {
    print $e->getMessage();
}            

Configure a proxy server

You can configure a proxy server for OSS SDK for PHP 5.3 or later.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
// Before you run the sample code, make sure that the access credentials are configured. The access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
$provider = new EnvironmentVariableCredentialsProvider();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the IP address of the proxy server. Format: http://<username>:<password>@<proxyip>:<proxyport>. 
$request_proxy = "yourRequestProxy"
try {
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "request_proxy"=> $request_proxy,
    );
    $ossClient = new OssClient($config);    
} catch (OssException $e) {
    print $e->getMessage();
}