Todos los productos
Search
Centro de documentos

Object Storage Service:Bloquear el acceso público a nivel de bucket (OSS SDK for PHP V2)

Última actualización: Sep 03, 2026

Puede utilizar OSS SDK for PHP V2 para habilitar, consultar y eliminar la configuración de Block Public Access de un bucket.

Notas de uso

  • El código de ejemplo en este tema utiliza el ID de región cn-hangzhou correspondiente a la región China (Hangzhou). De forma predeterminada, se usa un endpoint público para acceder a los recursos de un bucket. Si desea acceder a los recursos del bucket desde otros servicios de Alibaba Cloud en la misma región donde se encuentra el bucket, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints que admite OSS, consulte Regions and endpoints.

Código de ejemplo

Habilitar Block Public Access para un bucket

A continuación se muestra cómo habilitar Block Public Access para un bucket.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

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

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

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

// Check whether required arguments are specified.
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);
    }
}

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

// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

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

// Set the credentials 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);

// Build a PutBucketPublicAccessBlockRequest object to set the Block Public Access configuration for the bucket.
$request = new Oss\Models\PutBucketPublicAccessBlockRequest(
    bucket: $bucket,
    publicAccessBlockConfiguration: new Oss\Models\PublicAccessBlockConfiguration(blockPublicAccess: true) // Configure to block public access.
);

// Call the putBucketPublicAccessBlock method to set the Block Public Access configuration for the bucket and accept the result.
$result = $client->putBucketPublicAccessBlock($request);

// Print the result, including the status code and request ID.
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId
);

Obtener la configuración de Block Public Access de un bucket específico

A continuación se muestra cómo consultar la configuración de Block Public Access de un bucket.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

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

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

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

// Check whether required arguments are specified.
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);
    }
}

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

// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

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

// Set the credentials 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);

// Build a GetBucketPublicAccessBlockRequest object to obtain the Block Public Access configuration of the bucket.
$request = new Oss\Models\GetBucketPublicAccessBlockRequest(bucket: $bucket);

// Call the getBucketPublicAccessBlock method to obtain the Block Public Access configuration of the bucket and accept the result.
$result = $client->getBucketPublicAccessBlock($request);

// Print the result, including the status code, request ID, and Block Public Access configuration.
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId . PHP_EOL .
    'bucket public access block config:' . var_export($result->publicAccessBlockConfiguration, true)
);

Eliminar la configuración de Block Public Access de un bucket específico

A continuación se muestra cómo eliminar la configuración de Block Public Access de un bucket.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

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

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

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

// Check whether required arguments are specified.
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);
    }
}

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

// Load credentials, including the AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

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

// Set the credentials 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);

// Build a DeleteBucketPublicAccessBlockRequest object to delete the Block Public Access configuration of the bucket.
$request = new Oss\Models\DeleteBucketPublicAccessBlockRequest(bucket: $bucket);

// Call the deleteBucketPublicAccessBlock method to delete the Block Public Access configuration of the bucket and accept the result.
$result = $client->deleteBucketPublicAccessBlock($request);

// Print the result, including the status code and request ID.
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId
);

Referencias

  • Para ver el código de ejemplo completo sobre cómo gestionar Block Public Access a nivel de bucket, visite GitHub.

  • Para obtener más información sobre la operación de API utilizada para habilitar Block Public Access en un bucket, consulte PutBucketPublicAccessBlock.

  • Para obtener más información sobre la operación de API utilizada para recuperar la configuración de Block Public Access de un bucket, consulte GetBucketPublicAccessBlock.

  • Para obtener más información sobre la operación de API utilizada para eliminar la configuración de Block Public Access de un bucket, consulte DeleteBucketPublicAccessBlock.