All Products
Search
Document Center

Object Storage Service:Upgrade OSS SDK for PHP from 1.0 to 2.0

Last Updated:May 09, 2025

OSS SDK for PHP 2.0 is a complete refactoring of 1.0, streamlining core operations such as authentication, request retries, and error handling. It offers more flexible parameter configurations and introduces new advanced features, including an improved paginator and file transfer managers. This topic describes how to upgrade OSS SDK for PHP from 1.0 to 2.0.

Procedure

Step 1: Prepare the environment

  1. Review existing code

    • Examine the current codebase to identify where OSS SDK for PHP is implemented.

    • Record the specific OSS features and API operations utilized.

    • Identify any dependencies tied to the current SDK version to prevent issues during an upgrade.

  2. Update the PHP runtime environment

    • OSS SDK for PHP 2.0 requires that the version of PHP must be 7.4 or later.

  3. Retain OSS SDK for PHP 1.0 to facilitate a smooth transition to 2.0

    1. Install by using composer

      If your project uses composer for dependency management, run the following command in the project's root folder:

      composer require alibabacloud/oss-v2

      Alternatively, declare the required dependencies for OSS SDK for PHP 2.0 directly in your composer.json file.

      "require": {    "alibabacloud/oss-v2": "*"
      }

      Then, run the composer install command to install the dependencies.

    2. Install by using a PHAR file

      require_once '/path/to/alibabacloud-oss-php-sdk-v2-{version}.phar'
  4. Create a test environment

    • Set up a separate test environment rather than changing parameters directly in the production environment.

    • Configure test data and test cases to check the upgraded code.

Step 2: Modify import statements

Feature changes

OSS SDK for PHP 2.0 has moved to a new repository (alibabacloud-oss-php-sdk-v2) and features a restructured codebase organized by feature modules, enhancing readability and maintainability. The following table describes the modules.

Module path

Description

github.com/aliyun/alibabacloud-oss-php-sdk-v2/src

The core of OSS SDK for PHP, which is used to implement both basic and advanced API operations.

github.com/aliyun/alibabacloud-oss-php-sdk-v2/src/Credentials

The access credentials.

github.com/aliyun/alibabacloud-oss-php-sdk-v2/src/Retry

The retry mechanism.

github.com/aliyun/alibabacloud-oss-php-sdk-v2/src/Signer

The signature.

github.com/aliyun/alibabacloud-oss-php-sdk-v2/src/Annotation

The annotation related to tag and XML conversion

github.com/aliyun/alibabacloud-oss-php-sdk-v2/src/Crypto

The client-side encryption.

github.com/aliyun/alibabacloud-oss-php-sdk-v2/src/Models

The request and response objects.

github.com/aliyun/alibabacloud-oss-php-sdk-v2/src/Paginator

The paginator.

github.com/aliyun/alibabacloud-oss-php-sdk-v2/src/Exception

The exception handeling.

github.com/aliyun/alibabacloud-oss-php-sdk-v2/src/Types

The types.

Sample code

# OSS SDK for PHP 1.0
require_once 'vendor/autoload.php';
use OSS\OssClient;

# OSS SDK for PHP 2.0
require_once  'vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;

Step 3: Modify the code used to create an OSSClient instance

Feature changes

  1. OSS SDK for PHP 2.0 streamlines configuration management by importing settings into config. It also includes auxiliary functions prefixed with set to allow programmatically overriding default configurations.

  2. OSS SDK for PHP 2.0 defaults to the V4 signature algorithm. When configuring the OSSClient instance, you must specify an Alibaba Cloud region ID to identify the request's origin region.

  3. OSS SDK for PHP 2.0 automatically generates an endpoint based on your selected region. When you access a public endpoint, no manual endpoint configuration is required—the system dynamically determines the endpoint by using your region details.

Sample code

Example of OSS SDK for PHP 1.0

require_once 'vendor/autoload.php';
use OSS\OssClient;
...

// Obtain access credentials from environment variables.
$provider = new \OSS\Credentials\EnvironmentVariableCredentialsProvider();

// Endpoint
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

$config = array(
       "provider" => $provider,
       "endpoint" => $endpoint,
       "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
       "region" => "cn-hangzhou"
   );
$ossClient = new OssClient($config);
// Do not verify SSL certificates.
$ossClient->setUseSSL(false);

Example of OSS SDK for PHP 2.0

To use the new configuration loading mode in OSS SDK for PHP 2.0, you must first create a configuration object (cfg) and provide the required information, such as the region.

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

// Obtain access credentials from environment variables.
$provider = new \OSS\Credentials\EnvironmentVariableCredentialsProvider();

$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
// Set the timeout period of an HTTP connection to 20. Unit: seconds.
$cfg->setConnectTimeout(20);
// Set the read or write timeout period of an HTTP connection to 60. Unit: seconds.
$cfg->setReadWriteTimeout(60);
// Do not verify SSL certificates.
$cfg->setDisableSSL(true);
// Specify the region.
$cfg->setRegion('cn-hangzhou');
$client = new Oss\Client($cfg);

For information about how to configure an OSSClient instance for OSS SDK for PHP 2.0, see Configure an OSSClient instance.

Step 4: Modify the basic API calling method

Feature changes

  1. OSS SDK for PHP 2.0 provides basic (low-level) API operations, which map directly to REST API interfaces. You can call basic API operations to manage OSS resources, including creating a bucket, uploading objects, and downloading objects.

  2. In OSS SDK for PHP 2.0, each basic API operation adheres to a standard naming convention. Operations are named in the <OperationName> format, where the corresponding request class is defined as <OperationName>Request and the response class is defined as <OperationName>Result, as shown in the following code.

    public function <operationName>(Models\<OperationName>Request $request, array $args = []): Models\<OperationName>Result
    public function <operationName>Async(Models\<OperationName>Request $request, array $args = []): \GuzzleHttp\Promise\Promise

For more information about basic API operations, see Basic API operations.

Sample code

Example of OSS SDK for PHP 1.0

require_once 'vendor/autoload.php';
use OSS\OssClient;
$provider = new \OSS\Credentials\EnvironmentVariableCredentialsProvider();
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
$config = array(
    "provider" => $provider,
    "endpoint" => $endpoint,
    "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
    "region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
$ossClient->putObject('examplebucket','exampleobject.txt','example data');

Example of OSS SDK for PHP 2.0

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

$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion('cn-hangzhou');
$ossClient = new Oss\Client($cfg);

$client->putObject(
    new Oss\Models\PutObjectRequest(
        bucket: 'examplebucket',
        key: 'exampleobject.txt',
        body:  Oss\Utils::streamFor('example data'),
    ),
);

(Optional) Step 5: Modify the advanced API calling method

API operation for generating a presigned URL

Feature changes

In OSS SDK for PHP 2.0, the name of the API operation used to generate a presigned URL is changed from sign_url to presign, as shown in the following code.

public function presign(request: $request,args: $options): Models\PresignResult

The request parameters use the same type as the <OperationName>Request defined in the API operation.

The response contains a presigned URL along with the required HTTP method, the URL's expiration time, and the signed request headers. Example:

final class PresignResult
{
    public ?string $method;
    
    public ?string $url;
    
    public ?\DateTime $expiration;
    
    public ?array $signedHeaders;
}

For more information, see Operation used to generate a presigned URL.

Sample code

Example of OSS SDK for PHP 1.0

require_once 'vendor/autoload.php';
use OSS\OssClient;
$provider = new \OSS\Credentials\EnvironmentVariableCredentialsProvider();
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
$config = array(
    "provider" => $provider,
    "endpoint" => $endpoint,
    "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
    "region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
$url = $ossClient->signUrl('examplebucket','exampleobject.txt',60,OssClient::OSS_HTTP_GET);

printf("Sign Url:%s\n", $url);

Example of OSS SDK for PHP 2.0

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

$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion('cn-hangzhou');
$ossClient = new Oss\Client($cfg);

$result = $ossClient->presign(
    new Oss\Models\GetObjectRequest(
        bucket: 'examplebucket',
        key: 'exampleobject.txt',
    ),
    args: ['expiration' => (new \DateTime('now', new \DateTimeZone('UTC')))->add(new DateInterval('PT60S'))],
);
print(
    'sign url:' . $result->url . PHP_EOL .
    'sign method :' . $result->method . PHP_EOL .
    'sign expiration:' . var_export($result->expiration, true) . PHP_EOL .
    'sign headers:' . var_export($result->signedHeaders, true) . PHP_EOL
);

For the complete sample code that is used to upload an object by using a presigned URL, see Use a presigned URL to upload an object.

File transfer managers

Feature changes

OSS SDK for PHP 2.0 uses dedicated file transfer managers—Uploader, Downloader, and Copier—to handle object uploads, downloads, and copy operations, respectively. For more information about how to use file transfer managers in OSS SDK for PHP 2.0, see Developer Guide > Transfer managers.

Sample code
  1. Use Uploader to upload an object

    ...
    $client = new Oss\Client($cfg);
    $u = $client->newUploader();
    $result = $u->uploadFile(
        new Oss\Models\PutObjectRequest(
            bucket: 'bucket',
            key: 'key'
        ),
        filepath: '/local/dir/example',
    );
    printf(
        'upload file status code:' . $result->statusCode . PHP_EOL .
        'upload file request id:' . $result->requestId . PHP_EOL .
        'upload file result:' . var_export($result, true) . PHP_EOL
    );

    For more information about how to use Uploader of OSS SDK for PHP 2.0, see Uploader.

    For the complete sample code that is used to upload an object by using Uploader of OSS SDK for PHP 2.0, see Use Uploader to upload objects.

  2. Use Downloader to download an object

    ...
    $client = new Oss\Client($cfg);
    $d = $client->newDownloader();
    $d->downloadFile(
        new Oss\Models\GetObjectRequest(
            bucket: 'bucket',
            key: 'key'
        ),
        filepath: '/local/dir/example',
    );

    For more information about how to use Downloader of OSS SDK for PHP 2.0, see Downloader.

    For the complete sample code that is used to upload an object by using Downloader of OSS SDK for PHP 2.0, see Use Downloader to download objects.

  3. Use Copier to copy an object

    ...
    $client = new Oss\Client($cfg);
    $c = $client->newCopier();
    $result = $c->copy(
        new Oss\Models\CopyObjectRequest(
            bucket: 'bucket',
            key: 'key',
            sourceBucket: 'src-bucket',
            sourceKey: 'src-key',
        )
    );
    printf(
        'status code:' . $result->statusCode . PHP_EOL .
        'request id:' . $result->requestId . PHP_EOL .
        'result:' . var_export($result, true)
    );

    For more information about how to use Copier of OSS SDK for PHP 2.0, see Copier.

Step 6: Verify the upgrade

  1. Unit tests

    To ensure OSS SDK for PHP 2.0 functions as intended, compile comprehensive test cases for each upgraded feature. These tests should cover all critical operations and validate that the results match those of OSS SDK for PHP 1.0. Key operations:

    • Basic deature testing: Verify core features, including creating resources, checking states, updating data, and deleting resources.

    • Boundary condition testing: Assess application behavior in extreme scenarios, such as processing very large or very small datasets and handling abnormal inputs.

    • Error handling testing: Ensure the application properly manages errors (such as network timeouts and invalid inputs) and provides appropriate feedback.

  2. Incremental upgrades and tests

    Upgrade and test OSS SDK for PHP in small, manageable steps to minimize risks.

    • Start with a small, independent module: Begin by upgrading and thoroughly testing a simple, isolated module. Ensure complete test coverage for this module before proceeding.

    • Expand testing gradually: Once the initial module is successfully upgraded and validated, proceed to upgrade and test additional modules step by step. This helps catch and fix issues early, avoiding large-scale rollbacks.

  3. Compatibility tests

    Verify that OSS SDK for PHP 2.0 works correctly with your full technology stack and all dependencies.

    • Internal system compatibility: Confirm that OSS SDK for PHP 2.0 is compatible with your existing internal systems and architectures.

    • Third-party service compatibility: If your application relies on third-party services or APIs, test their compatibility with OSS SDK for PHP 2.0 to ensure expected functionality.

    • Environment compatibility: Test OSS SDK for PHP 2.0 across different operating systems and runtime environments to ensure proper operation in all required setups.

  4. Performance tests

    After upgrading OSS SDK for PHP from 1.0 to 2.0, assess your application's performance.

    • Benchmark testing: Establish performance benchmarks for the current application. Record key metrics, including response time and throughput.

    • Comparative analysis: After you upgrade OSS SDK for PHP from 1.0 to 2.0, test both versions under identical conditions. Compare performance to ensure OSS SDK for PHP 2.0 does not show significant degradation.

    • Tuning: If OSS SDK for PHP 2.0 exhibits performance decline, adjust parameter configurations and optimize code logic for better efficiency.

Differences between 1.0 and 2.0

Item

Version 1.0

Version 2.0

PHP version

  • PHP 5.3 or later

  • PHP 7.4 or later

  • PHP 8.0 or later required for bucket-related operations

Code for obtaining the SDK

composer require aliyuncs/oss-sdk-php
composer require alibabacloud/oss-v2

Signature algorithm

  • Defaults to the V1 signature algorithm.

  • Defaults to the V4 signature algorithm.

  • The Region parameter is required.

Configuration loading

  • The configured methods are scattered across multiple locations.

  • Defaults to the V1 signature algorithm. The Region parameter is optional.

  • The Endpoint parameter is required.

  • Simplifies and imports configurations into config to programmatically override the default settings.

  • Defaults to the V4 signature algorithm. The Region parameter is required.

  • Allows you to create a region-specific endpoint. You can access a public endpoint, bypassing the need for manual endpoint selection.

API calling method

  • API operations lack standard naming rules.

  • Basic API operations follow a standard naming convention. For more information, see Basic API operations.

Operation used to generate a presigned URL

  • Operation: $ossClient->signUrl()

  • Returned result: the presigned URL

  • Operation: $client->presign()

  • Returned result: the presigned URL, the HTTP method, the URL's validity period, and the signed request headers.

Resumable transfer operation

None

  • Uploader: $client->newUploader()

  • Downloader: $client->newDownloader()

  • Copier: $client->newCopier()

Retry mechanism

A custom retry logic is required.

Failed HTTP requests are retried automatically.

References

For more information about how to upgrade OSS SDK for PHP from 1.0 to 2.0, see Developer Guide > Upgrade guidelines.