All Products
Search
Document Center

Object Storage Service:Initialization (PHP SDK V1)

Last Updated:Mar 20, 2026

OssClient is the PHP client for Object Storage Service (OSS). Initialize an OssClient instance before making any OSS requests.

Prerequisites

Before you begin, ensure that you have:

  • PHP 5.3 or later

  • OSS PHP SDK 2.7.0 or later (required for Signature V4)

  • Composer installed

Create an OssClient

Choose a credential method

MethodWhen to use
Environment variablesLocal development and CI/CD pipelines — credentials stay out of source code
STS temporary credentialsShort-lived access for applications running outside Alibaba Cloud
Instance RAM roleApplications running on Elastic Compute Service (ECS) — no credential management required
STSAssumeRoleCross-account or role-based access using a RAM user's AccessKey

Initialize with Signature V4 (recommended)

Supported in OSS PHP SDK 2.7.0 and later. Set signatureVersion to OssClient::OSS_SIGNATURE_VERSION_V4 and specify a region that matches the endpoint — for example, cn-hangzhou for https://oss-cn-hangzhou.aliyuncs.com.

Important

Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before running this code. Storing credentials in environment variables keeps them out of your source code.

<?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 {
    // Read credentials from environment variables
    $provider = new EnvironmentVariableCredentialsProvider();
    // Endpoint for the region where your bucket is located
    $endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    $config = array(
        "provider"         => $provider,
        "endpoint"         => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        // Region ID that corresponds to the endpoint
        "region"           => "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
} catch (OssException $e) {
    printf($e->getMessage() . "\n");
    return;
}

Initialize with Signature V1 (not recommended)

Important

From March 1, 2025, Signature V1 is unavailable to new customers with new UIDs. From September 1, 2025, OSS no longer maintains Signature V1, and it is unavailable for new buckets. Upgrade to Signature V4 as soon as possible.

OSS domain name

For endpoints of other 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\Core\OssException;

// OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET must be set in environment variables
$provider = new EnvironmentVariableCredentialsProvider();
// Endpoint for the China (Hangzhou) region — replace with your actual region 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();
}

Custom domain name

Important

listBuckets is not available when using a custom domain name.

Set cname to true and pass your custom domain as the endpoint. For setup instructions, see Access OSS using a custom domain name.

<?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;

// OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET must be set in environment variables
$provider = new EnvironmentVariableCredentialsProvider();
// Your custom domain name bound to the OSS bucket
$endpoint = "http://example.com";

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

STS

Use EnvironmentVariableCredentialsProvider to read an AccessKey ID, AccessKey secret, and STS security token from environment variables.

Important

Set the AccessKey pair and STS security token as environment variables before running this code.

<?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;

// OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and STS security token
// must be set in environment variables
$provider = new EnvironmentVariableCredentialsProvider();
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

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

Instance RAM role

An instance RAM role lets an Elastic Compute Service (ECS) instance fetch temporary credentials from STS automatically via instance metadata. The SDK retrieves and refreshes these credentials without manual key management.

Important

Install the Alibaba Cloud credentials package before running this code:

composer require alibabacloud/credentials
<?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(
    // Credential type for ECS instance RAM role — value is fixed
    'type'      => 'ecs_ram_role',
    // RAM role name attached to the ECS instance
    'role_name' => 'EcsRamRoleOssTest',
));

$providerWrapper = new AlibabaCloudCredentialsWrapper($ecsRamRole);
$provider = $providerWrapper->getCredentials();

$config = array(
    'provider' => $provider,
    'endpoint' => 'https://oss-cn-hangzhou.aliyuncs.com'
);

try {
    $ossClient = new OssClient($config);
} catch (OssException $e) {
    print $e->getMessage();
}

STSAssumeRole

Use a RAM user's AccessKey to assume a role and obtain temporary credentials via STS. The Alibaba Cloud Resource Name (ARN) of the role follows the format acs:ram::<accountID>:role/<roleName>.

Important

Install the Alibaba Cloud credentials package before running this code:

composer require alibabacloud/credentials
<?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(
    // Credential type for STSAssumeRole — value is fixed
    'type'              => 'ram_role_arn',
    // RAM user AccessKey — set YOUR_ACCESS_KEY_ID and YOUR_ACCESS_KEY_SECRET
    // as environment variables
    'access_key_id'     => getenv('YOUR_ACCESS_KEY_ID'),
    'access_key_secret' => getenv('YOUR_ACCESS_KEY_SECRET'),
    // ARN of the role to assume: acs:ram::<accountID>:role/<roleName>
    'role_arn'          => 'acs:ram::17464958********:role/ossststest',
    // Custom session name to distinguish tokens
    'role_session_name' => 'yourRoleSessionName',
    // Optional: restrict permissions with an inline policy
    'policy'            => '',
));

$providerWrapper = new AlibabaCloudCredentialsWrapper($ramRoleArn);
$provider = $providerWrapper->getCredentials();

$config = array(
    'provider' => $provider,
    'endpoint' => 'https://oss-cn-hangzhou.aliyuncs.com'
);

try {
    $ossClient = new OssClient($config);
} catch (OssException $e) {
    print $e->getMessage();
}

Configure an OssClient

Call the following setter methods after creating the client to adjust connection, retry, and SSL behavior.

ParameterDefaultUnitSetter
timeout5184000seconds$ossClient->setTimeout(60)
connectTimeout10seconds$ossClient->setConnectTimeout(600)
maxRetries3count$ossClient->setMaxTries(5)
useSSLfalseboolean$ossClient->setUseSSL(true)

useSSL controls SSL certificate verification. Set it to true to enable verification, or leave it at the default false to disable it.

<?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;

$provider = new EnvironmentVariableCredentialsProvider();
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

try {
    $config = array(
        "provider"         => $provider,
        "endpoint"         => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"           => "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    $ossClient->setConnectTimeout(300);  // Connection timeout: 300 seconds
    $ossClient->setMaxTries(5);          // Retry up to 5 times on failure
    $ossClient->setTimeout(30);          // Socket-level data timeout: 30 seconds
    $ossClient->setUseSSL(true);         // Enable SSL certificate verification
} catch (OssException $e) {
    print $e->getMessage();
}

Configure a proxy server

PHP 5.3 and later support proxy server configuration. Pass the proxy address as request_proxy in the constructor config array.

<?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;

$provider = new EnvironmentVariableCredentialsProvider();
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Proxy address format: http://<username>:<password>@<proxy_ip>:<proxy_port>
$request_proxy = "yourRequestProxy";

try {
    $config = array(
        "provider"         => $provider,
        "endpoint"         => $endpoint,
        "request_proxy"    => $request_proxy,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"           => "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
} catch (OssException $e) {
    print $e->getMessage();
}