All Products
Search
Document Center

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

Last Updated:Dec 05, 2025

Object Storage Service (OSS) provides server-side encryption for uploaded data. When you upload data, OSS encrypts and stores it. When you download the data, OSS automatically decrypts it and returns the original data. The HTTP response header indicates that the data was encrypted on the server.

Usage notes

  • Before you configure server-side encryption, ensure that you understand this feature. For more information, see Server-side encryption.

  • The sample code in this topic uses a public endpoint in the China (Hangzhou) region (cn-hangzhou) as an example. If you want to access OSS from other Alibaba Cloud products in the same region, you must use an internal network endpoint. For more information about the regions and endpoints that OSS supports, see Regions and endpoints.

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

Examples

Configure bucket encryption

You can use the following code to set the default encryption method for a bucket. After the configuration is complete, all objects uploaded to the bucket without a specified encryption method are encrypted using the bucket's default encryption method.

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // Required. The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // Optional. The domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required. The name of the bucket.
];

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) after each parameter indicates that a value is required.
}, array_keys($optsdesc));

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

// Check if required arguments are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

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

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

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

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

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

// Create a request object to set the bucket encryption configuration. Use the KMS encryption algorithm and specify SM4 as the data encryption method.
$request = new Oss\Models\PutBucketEncryptionRequest(
    bucket: $bucket, 
    serverSideEncryptionRule: new Oss\Models\ServerSideEncryptionRule(
        applyServerSideEncryptionByDefault: new Oss\Models\ApplyServerSideEncryptionByDefault(
            sseAlgorithm: 'KMS', // Use the KMS encryption algorithm.
            kmsDataEncryption: 'SM4' // The data encryption method is SM4.
    ))
);

// Call the putBucketEncryption method to set the encryption configuration for the bucket.
$result = $client->putBucketEncryption($request);

// Print the response.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId // The unique identifier of the request.
);

Get the bucket encryption configuration

You can use the following code to retrieve the bucket encryption configuration.

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // Required. The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // Optional. The domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required. The name of the bucket.
];

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) after each parameter indicates that a value is required.
}, array_keys($optsdesc));

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

// Check if required arguments are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

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

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

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

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

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

// Create a request object to get the bucket encryption configuration.
$request = new Oss\Models\GetBucketEncryptionRequest(bucket: $bucket);

// Call the getBucketEncryption method to get the encryption configuration of the bucket.
$result = $client->getBucketEncryption($request);

// Print the response.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId . PHP_EOL . // The unique identifier of the request.
    'encryption:' . var_export($result->serverSideEncryptionRule, true) // The encryption configuration.
);

Delete the bucket encryption configuration

You can use the following code to delete the bucket encryption configuration.

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // Required. The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // Optional. The domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required. The name of the bucket.
];

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) after each parameter indicates that a value is required.
}, array_keys($optsdesc));

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

// Check if required arguments are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

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

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

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

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

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

// Create a request object to delete the bucket encryption configuration.
$request = new Oss\Models\DeleteBucketEncryptionRequest(bucket: $bucket);

// Call the deleteBucketEncryption method to delete the encryption configuration of the bucket.
$result = $client->deleteBucketEncryption($request);

// Print the response.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId // The unique identifier of the request.
);

References