All Products
Search
Document Center

Object Storage Service:Server-side encryption (PHP SDK V2)

Last Updated:Aug 05, 2025

Object Storage Service (OSS) can encrypt uploaded data on the server. This is called server-side encryption. When you upload data to OSS, OSS encrypts the uploaded data and then persistently stores the encrypted data. When you download data from OSS, OSS decrypts the data and returns the decrypted data. In addition, a header is added to the response to declare that the data is encrypted on the server.

Usage notes

  • Before you configure server-side encryption, make sure that you are familiar with this feature. For more information, see Server-side encryption.

  • The sample code in this topic uses the region IDcn-hangzhou for the China (Hangzhou) region. By default, a public endpoint is used to access resources in a bucket. If you want to access resources in the bucket from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • To configure server-side encryption for a bucket, you must have the oss:PutBucketEncryption permission. To query the server-side encryption configuration of a bucket, you must have the oss:GetBucketEncryption permission. To delete the server-side encryption configuration of a bucket, you must have the oss:DeleteBucketEncryption permission. For more information, see Attach a custom policy to a RAM user.

Examples

Configure server-side encryption for a bucket

The following sample code provides examples on how to configure the default encryption method for a bucket. After you configure the default encryption method, all objects that are uploaded to the bucket without specifying an encryption method are encrypted using the default encryption method.

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

// Generate a long options list to parse the command line parameters.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts); 

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specify that the required parameters are not configured.
        exit(1); 
    }
}

// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Specify the region.
$cfg->setRegion($region);

// Specify the endpoint if an endpoint is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a PutBucketEncryptionRequest object, use the Key Management Service (KMS) encryption method, and set the encryption algorithm to SM4.
$request = new Oss\Models\PutBucketEncryptionRequest(
    bucket: $bucket, 
    serverSideEncryptionRule: new Oss\Models\ServerSideEncryptionRule(
        applyServerSideEncryptionByDefault: new Oss\Models\ApplyServerSideEncryptionByDefault(
            sseAlgorithm: 'KMS', //Use the KMS encryption method.
            kmsDataEncryption: 'SM4' // Set the encryption algorithm to SM4.
    ))
);

// Use the putBucketEncryption method to configure the server-side encryption configurations for the bucket.
$result = $client->putBucketEncryption($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId // The request ID of the request, which is the unique identifier of the request.
);

Query the server-side encryption configurations of a bucket

The following sample code provides an example on how to query the server-side encryption configurations of a bucket:

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

// Generate a long options list to parse the command line parameters.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts); 

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specify that the required parameters are not configured.
        exit(1); 
    }
}

// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Specify the region.
$cfg->setRegion($region);

// Specify the endpoint if an endpoint is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a GetBucketEncryptionRequest object to query the server-side encryption configurations of the bucket.
$request = new Oss\Models\GetBucketEncryptionRequest(bucket: $bucket);

// Use the getBucketEncryption method to query the server-side encryption configurations.
$result = $client->getBucketEncryption($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId . PHP_EOL . // The request ID of the request, which is the unique identifier of the request.
    'encryption:' . var_export($result->serverSideEncryptionRule, true) // The server-side encryption configurations.
);

Delete the server-side encryption configurations of a bucket

The following sample code provides an example on how to delete the server-side encryption configurations of a bucket:

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

// Generate a long options list to parse the command line parameters.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts); 

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specify that the required parameters are not configured.
        exit(1); 
    }
}

// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Specify the region.
$cfg->setRegion($region);

// Specify the endpoint if an endpoint is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a DeleteBucketEncryptionRequest object to delete the server-side encryption configurations of the bucket.
$request = new Oss\Models\DeleteBucketEncryptionRequest(bucket: $bucket);

// Use the deleteBucketEncryption method to delete the server-side encryption configurations of the bucket.
$result = $client->deleteBucketEncryption($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId // The request ID of the request, which is the unique identifier of the request.
);

References