Todos los productos
Search
Centro de documentos

Object Storage Service:Crear buckets con OSS SDK for PHP 2.0

Última actualización: Sep 22, 2026

Un bucket es un contenedor para almacenar objetos. Puede usar Object Storage Service (OSS) SDK for PHP para crear buckets.

Notas

  • El código de ejemplo usa el ID de región cn-hangzhou, correspondiente a la región China (Hangzhou), y el endpoint público de forma predeterminada. Para acceder a los recursos de un bucket desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles, consulte OSS regions and endpoints.

  • Para crear buckets se requiere el permiso oss:PutBucket. Para más detalles, consulte Grant a custom policy.

  • A partir de las 10:00:00 (UTC+8) del 13 de octubre de 2025, OSS habilitará gradualmente Block public access de forma predeterminada en todos los buckets que se creen mediante llamadas a operaciones de API o con OSS SDKs y ossutil, en todas las regiones. Para conocer la fecha exacta en que este cambio entrará en vigor en cada región, consulte Anuncio. Una vez habilitada esta función, no podrá otorgar permisos de acceso público. Esto incluye la ACL public-read o public-read-write, así como políticas de bucket que permitan dicho acceso. Si su negocio requiere acceso público, deshabilite el bloqueo de acceso público después de crear el bucket.

Código de ejemplo

A continuación se muestra el código de ejemplo para crear un bucket.

<?php

// Automaticically load objects and dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php'; 

use AlibabaCloud\Oss\V2 as Oss;

// Specify command line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region parameter is required. Example: oss-cn-hangzhou.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint parameter is optional.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The name of the bucket is required.
];

// Generate a list of long options for parsing command line parameters.
$longopts = \array_map(function ($key) {
    return "$key:"; // The colon (:) following each parameter indicates that the parameter is required.
}, array_keys($optsdesc));

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

// Check whether the required parameters have been 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"; // Specifies that the required parameters are not configured.
        exit(1); 
    }
}

// Retrieve the values of the command line parameters.
$region = $options["region"]; // Region in which the bucket is located.
$bucket = $options["bucket"]; // Name of the bucket.

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

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault(); 
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}

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

// Create a request to initiate bucket creation.
$request = new Oss\Models\PutBucketRequest($bucket); 

// Call the putBucket method.
$result = $client->putBucket($request);

// Output the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // HTTP status code.
    'request id:' . $result->requestId // Unique ID of the request.
);

Referencias

  • Para consultar el código de ejemplo completo, visite el ejemplo en GitHub.

  • Para conocer la operación de API utilizada para crear buckets, consulte PutBucket.