Todos los productos
Search
Centro de documentos

Object Storage Service:OSS SDK for PHP 2.0

Última actualización: Sep 03, 2026

GitHub | Guía del desarrollador de OSS SDK para PHP 2.0 | Versiones del SDK

Integración rápida

image

Requisitos previos

OSS SDK para PHP 2.0 es compatible con PHP 7.4 o versiones posteriores. El código de ejemplo de este documento utiliza argumentos con nombre de PHP 8, por lo que requiere PHP 8.0 o superior. Descargue Composer para la gestión de paquetes.

Ejecute el comando php -version para comprobar la versión de PHP. Si PHP no está instalado o la versión es anterior a la 8.0, descargue e instale PHP .

Instalar el SDK

  1. Cree un directorio de proyecto y ejecute el siguiente comando para instalar OSS SDK para PHP 2.0 mediante Composer. Utilice la versión más reciente para garantizar la compatibilidad del código de ejemplo.

    mkdir oss-php-example && cd oss-php-example && composer require alibabacloud/oss-v2
  2. Importe el paquete de OSS SDK para PHP 2.0:

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

Configurar las credenciales de acceso

Configure las credenciales de acceso mediante el par de AccessKey de un usuario de RAM.

  1. En la consola de RAM, cree un usuario de RAM con un AccessKey Pair permanente. Guarde el par de AccessKey y otorgue el permiso AliyunOSSFullAccess al usuario de RAM.

  2. Utilice el par de AccessKey del usuario de RAM para configurar las variables de entorno.

    Linux

    1. Ejecute los siguientes comandos para agregar la configuración de las variables de entorno al archivo ~/.bashrc .

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Ejecute el siguiente comando para aplicar los cambios.

        source ~/.bashrc
      2. Ejecute los siguientes comandos para comprobar si las variables de entorno están configuradas.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Ejecute el siguiente comando en la terminal para ver el tipo de shell predeterminado.

      echo $SHELL
      1. Realice los siguientes pasos según el tipo de shell predeterminado.

        Zsh

        1. Ejecute los siguientes comandos para agregar la configuración de las variables de entorno al archivo ~/.zshrc.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Ejecute el siguiente comando para aplicar los cambios.

          source ~/.zshrc
        3. Ejecute los siguientes comandos para comprobar si las variables de entorno están configuradas.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Ejecute los siguientes comandos para agregar la configuración de las variables de entorno al archivo ~/.bash_profile.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        2. Ejecute el siguiente comando para aplicar los cambios.

          source ~/.bash_profile
        3. Ejecute los siguientes comandos para comprobar si las variables de entorno están configuradas.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Ejecute los siguientes comandos en la ventana del Símbolo del sistema.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Ejecute los siguientes comandos para comprobar si las variables de entorno están configuradas.

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Ejecute los siguientes comandos en PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      1. Ejecute los siguientes comandos para comprobar si las variables de entorno están configuradas.

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Inicializar el cliente

Importante

Debido a un cambio de directiva para mejorar el cumplimiento y la seguridad, a partir del 20 de marzo de 2025, los nuevos usuarios de OSS deben use a custom domain name (CNAME) para realizar operaciones de API de datos en buckets de OSS ubicados en regiones de China continental. Los endpoints públicos predeterminados tienen restricciones para estas operaciones. Consulte el anuncio oficial para obtener una lista completa de las operaciones afectadas. Si accede a sus datos mediante HTTPS, debe bind a valid SSL Certificate a su dominio personalizado. Esto es obligatorio para el acceso a la consola de OSS, ya que la consola exige el uso de HTTPS.

Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como <region-id> con su region and endpoint real, por ejemplo, ap-southeast-1 .
<?php

/**
 * Complete guide to OSS SDK for PHP 2.0 client configuration
 *
 * ===========================================
 * V4 signature and region configuration
 * ===========================================
 * • OSS SDK for PHP 2.0 uses the V4 signature algorithm by default.
 * • You must specify an Alibaba Cloud region ID when initializing the client.
 * • For a list of region IDs, see Regions and endpoints.
 *
 * ===========================================
 * Endpoint configuration
 * ===========================================
 * • The SDK lets you customize the service endpoint by using the endpoint parameter.
 * • If you omit the endpoint, the SDK automatically constructs a public endpoint from the region information.
 * • For example, if the region is '<region-id>', the constructed endpoint is 'https://oss-<region-id>.aliyuncs.com'.
 *
 * ===========================================
 * Protocol selection
 * ===========================================
 * • The SDK uses HTTPS by default to construct endpoints, which is the recommended protocol.
 * • To use the HTTP protocol, include http:// in the endpoint.
 * • HTTPS example: 'https://oss-<region-id>.aliyuncs.com'
 * • HTTP example: 'http://oss-<region-id>.aliyuncs.com'
 */

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

use AlibabaCloud\Oss\V2 as Oss;

// EnvironmentVariableCredentialsProvider reads the AccessKey ID and AccessKey Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);

// Method 1: Specify only the region (recommended). The SDK automatically constructs an HTTPS endpoint.
$cfg->setRegion(region: "<region-id>");

// // Method 2: Specify both the region and the endpoint.
// $cfg->setRegion(region: '<region-id>')->setEndpoint(endpoint: 'https://oss-<region-id>.aliyuncs.com');

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

// The data to upload.
$data = 'Hello OSS';

// Create a PutObjectRequest object to upload an object.
$request = new Oss\Models\PutObjectRequest(
                bucket: "Your Bucket Name",
                key: "Your Object Key",
            );
$request->body = Oss\Utils::streamFor($data); // Set the request body to a data stream.

// Perform the upload operation.
$result = $client->putObject($request);

// Print the upload result.
printf(
    'status code: %s' . PHP_EOL . // The HTTP status code.
    'request id: %s' . PHP_EOL .  // The request ID.
    'etag: %s' . PHP_EOL,         // The ETag of the object.
    $result->statusCode,
    $result->requestId,
    $result->etag
);

Salida esperada tras una carga exitosa:

status code: 200
request id: 687F2BEEDC44E0313527BA07
etag: "F0F18C2C66AE1DD512BDCD4366F76DA3"

Configuraciones del cliente

¿Cuáles son las configuraciones de cliente compatibles?

Parámetro

Descripción

Ejemplo

region

(Obligatorio) La región de destino para las solicitudes.

setRegion("<region-id>")

credentialsProvider

(Obligatorio) El proveedor de credenciales de acceso.

setCredentialsProvider(provider)

endpoint

El endpoint.

setEndpoint("oss-cn-hangzhou.aliyuncs.com")

retryMaxAttempts

El número máximo de reintentos para una solicitud HTTP. El valor predeterminado es 3.

setRetryMaxAttempts(5)

retryer

La implementación de reintentos para una solicitud HTTP.

setRetryer(customRetryer)

connectTimeout

El tiempo de espera para establecer una conexión. El valor predeterminado es 10 segundos.

setConnectTimeout(5)

readWriteTimeout

El tiempo de espera para lectura y escritura de datos. El valor predeterminado es 20 segundos.

setReadwriteTimeout(30)

insecureSkipVerify

Especifica si se omite la verificación del certificado SSL. De forma predeterminada, los certificados SSL se verifican.

setInsecureSkipVerify(true)

enabledRedirect

Especifica si se habilita la redirección HTTP. De forma predeterminada, esta función está deshabilitada.

setEnabledRedirect(true)

proxyHost

Configurar un servidor proxy

setProxyHost('http://user:password@proxy.example-***.com')

signatureVersion

La versión de la firma. El valor predeterminado es v4.

setSignatureVersion("v1")

disableSSL

Especifica si se utilizan solicitudes HTTPS. De forma predeterminada, se usa HTTPS.

setDisableSSL(true)

usePathStyle

Especifica si se utilizan URL con estilo de ruta. De forma predeterminada, se usan URL con estilo de host virtual.

setUsePathStyle(true)

useCName

Especifica si se utiliza un nombre de dominio personalizado. De forma predeterminada, no se usan nombres de dominio personalizados.

setUseCName(true)

useDualStackEndpoint

Especifica si se utiliza un endpoint de pila doble. De forma predeterminada, no se usan endpoints de pila doble.

setUseDualStackEndpoint(true)

useAccelerateEndpoint

Especifica si se utiliza un endpoint de aceleración. De forma predeterminada, no se usan endpoints de aceleración.

setUseAccelerateEndpoint(true)

useInternalEndpoint

Especifica si se utiliza un endpoint interno. De forma predeterminada, no se usan endpoints internos.

setUseInternalEndpoint(true)

additionalHeaders

Los encabezados de solicitud adicionales que se firmarán. Este parámetro solo es válido para firmas V4.

setAdditionalHeaders(['content-length'])

userAgent

La información adicional de User-Agent.

setUserAgent('user identifier')

Usar un nombre de dominio personalizado

Para habilitar la vista previa de archivos en el navegador y la aceleración de CDN, bind a custom domain name to your bucket.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Use EnvironmentVariableCredentialsProvider to obtain the AccessKey ID and AccessKey Secret from environment variables. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Load the default SDK configuration and set the credential provider. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Specify your custom domain name, such as www.example-***.com. // Note: setUseCname must be set to true to use a custom domain name. // Calling the PutCname operation requires PHP 8 or later. $cfg->setRegion('<region-id>')->setEndpoint('www.example-***.com')->setUseCname(true); // Create an OSS client instance. $client = new Oss\Client($cfg); // Use the created client for subsequent operations...

Control de tiempo de espera

<?php

// Load dependencies from the autoload file.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

# Load the default SDK configuration.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.

$cfg->setRegion(region: "<region-id>");

# Set the connection timeout.
$cfg->setConnectTimeout(connectTimeout: 30);

# Set the read/write timeout.
$cfg->setReadwriteTimeout(readwriteTimeout:30);

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

// Use the created client for subsequent operations...

Número máximo de reintentos

De forma predeterminada, OSSClient reintenta las solicitudes con errores 3 veces.

Para escenarios de alta concurrencia o redes inestables, aumente los reintentos con setRetryMaxAttempts.

<?php

// Include the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

# Load the default SDK configuration and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);

$cfg->setRegion(region: "<region-id>");

// Set the maximum number of attempts for an HTTP request. The default value is 3.
$cfg->setRetryMaxAttempts(5);

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

// Use the created client for subsequent operations...

Protocolo HTTP/HTTPS

Puede usar setDisableSSL(true) para deshabilitar el protocolo HTTPS.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Create a credential provider that reads the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configuration and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);

$cfg->setRegion(region: "<region-id>");

// Disable SSL.
$cfg->setDisableSSL(true);

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

// Use the client for OSS operations.

Uso de corrutinas en el framework Swoole

El siguiente código muestra un ejemplo de cómo crear un cliente de OSS compatible con corrutinas basado en el framework Swoole.

<?php
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;
use GuzzleHttp\HandlerStack;
use Hyperf\Guzzle\CoroutineHandler;
use function Hyperf\Coroutine\co;

// Configure the OSS client.
$region = '<region-id>'; // The OSS region.
$bucket = 'bucket-name'; // The destination bucket.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Load credentials from environment variables.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.
$cfg->setRegion(region: $region); // Set the region.
$cfg->setEndpoint(endpoint: 'http://oss-<region-id>.aliyuncs.com'); // Set the endpoint.

// Create an OSS client that supports coroutines.
$client = new Oss\Client(config: $cfg, options: ['handler' => HandlerStack::create(handler: new CoroutineHandler())]);

// Coroutine task 1: Upload swoole.txt.
co(function () use ($client, $bucket) {
    try {
        $key = 'swoole.txt'; // The object name.
        $data = 'Hello OSS'; // The object content.
        $request = new Oss\Models\PutObjectRequest($bucket, $key); // Create an upload request.
        $request->body = Oss\Utils::streamFor($data); // Set the request body.
        $result = $client->putObject(request: $request); // Perform the upload.
        echo "Task 1 Result:\n" . var_export($result, true) . "\n"; // Print the result.
    } catch (\Exception $e) {
        echo "Task 1 Error: " . $e->getMessage() . "\n"; // Catch the exception.
    }
});

// Coroutine task 2: Upload hyperf.txt.
co(function () use ($client, $bucket) {
    try {
        $key = 'hyperf.txt'; // The object name.
        $data = 'Hello OSS'; // The object content.
        $request = new Oss\Models\PutObjectRequest($bucket, $key); // Create an upload request.
        $request->body = Oss\Utils::streamFor($data); // Set the request body.
        $result = $client->putObject($request); // Perform the upload.
        echo "Task 2 Result:\n" . var_export($result, true) . "\n"; // Print the result.
    } catch (\Exception $e) {
        echo "Task 2 Error: " . $e->getMessage() . "\n"; // Catch the exception.
    }
});

Uso de un endpoint interno

Si su aplicación está desplegada en una instancia ECS de Alibaba Cloud y necesita acceder frecuentemente a recursos de OSS en la misma región, puede utilizar un endpoint interno para reducir los costos de tráfico y mejorar la velocidad de acceso.

<?php

// Include the autoload file to load dependencies correctly.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Create a credential provider that reads the AccessKey ID and AccessKey Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK config and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);

// Method 1: Specify the region and set setUseInternalEndpoint to true.
$cfg->setRegion('<region-id>')->setUseInternalEndpoint(true);

// // Method 2: Directly specify the region and endpoint.
// // Specify the internal endpoint for the region where the bucket is located.
// // To use the HTTP protocol, set the endpoint to 'http://oss-<region-id>-internal.aliyuncs.com'.
// $cfg->setRegion('<region-id>')->setEndpoint('https://oss-<region-id>-internal.aliyuncs.com');

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

// Use the created client for subsequent operations...

Uso de un endpoint de aceleración

<?php

// Load project dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Read the AccessKey ID and AccessKey Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configuration and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);

// Method 1: Specify the region and set setUseAccelerateEndpoint to true.
$cfg->setRegion('<region-id>')->setUseAccelerateEndpoint(true);

// // Method 2: Directly specify the region and endpoint.
// // Specify the regional acceleration endpoint.
// $cfg->setRegion('<region-id>')->setEndpoint('https://oss-accelerate.aliyuncs.com');

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

// Use this client for subsequent operations.

Uso de un dominio privado

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Create a credential provider that reads the AccessKey ID and AccessKey Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider);

// Specify the region and set the endpoint to your private domain.
$cfg->setRegion('<region-id>')->setEndpoint('https://service.corp.example.com');

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

// Use the created client for subsequent operations...

Uso de un endpoint de Alibaba Gov Cloud

El siguiente código muestra un ejemplo de cómo configurar OSSClient mediante un endpoint de Gov cloud.

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

# Load the default SDK configurations and set the credential provider.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider(credentialsProvider: $credentialsProvider); // Set the credential provider.

// Specify the region where the bucket is located. For example, for China (Beijing) Alibaba Gov Cloud 1, set the region to cn-north-2-gov-1.
// Specify the internal endpoint of the bucket's region. For example, for China (Beijing) Alibaba Gov Cloud 1, set the endpoint to 'https://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
// To use the HTTP protocol, set the endpoint to 'http://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
$cfg->setRegion('cn-north-2-gov-1')->setEndpoint('https://oss-cn-north-2-gov-1-internal.aliyuncs.com');

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

// Use the created client for subsequent operations.

Configuraciones de credenciales de acceso

Seleccione un método de credenciales según sus requisitos de autenticación.

¿Cómo selecciono las credenciales de acceso?

Método de inicialización del proveedor de credenciales

Escenarios

Requiere un par de AccessKey o token de STS preexistente

Credencial subyacente

Periodo de validez de la credencial

Método de rotación o renovación de credenciales

Uso del par de AccessKey de un usuario de RAM

Aplicaciones desplegadas en un entorno seguro y estable, no susceptibles a ataques externos. Estas aplicaciones requieren acceso a largo plazo a los servicios de Alibaba Cloud sin rotación frecuente de credenciales.

Sí

Par de AccessKey

Largo plazo

Rotación manual

Uso de un token de STS

Aplicaciones desplegadas en un entorno no confiable. Desea controlar el periodo de validez y los permisos de acceso.

Sí

Token de STS

Temporal

Renovación manual

Uso de un ARN de rol de RAM

Aplicaciones que requieren acceso autorizado a servicios de Alibaba Cloud, como el acceso entre cuentas.

Sí

Token de STS

Temporal

Renovación automática

Uso de un rol de RAM de instancia

Aplicaciones desplegadas en instancias ECS de Alibaba Cloud, instancias ECI o nodos worker de Container Service for Kubernetes.

No

Token de STS

Temporal

Renovación automática

Uso de un ARN de rol OIDC

Aplicaciones no confiables desplegadas en nodos worker de Container Service for Kubernetes.

No

Token de STS

Temporal

Renovación automática

Proveedor de credenciales personalizado

Si ninguno de los métodos de configuración de credenciales anteriores satisface sus necesidades, puede personalizar el método para obtener credenciales.

Personalizado

Personalizado

Personalizado

Personalizado

Uso del par de AccessKey de un usuario de RAM

Inicialice el proveedor de credenciales con el par de AccessKey de una cuenta de Alibaba Cloud o un usuario de RAM. Adecuado para entornos seguros que requieren acceso a OSS a largo plazo sin rotación frecuente de credenciales. Este método requiere mantenimiento manual de AccessKey, lo que incrementa los riesgos de seguridad.

Aviso
  • Una cuenta de Alibaba Cloud tiene permisos completos sobre todos los recursos. La filtración del par de AccessKey representa riesgos de seguridad significativos. Utilice el par de AccessKey de un usuario de RAM con los permisos mínimos necesarios.

  • Para obtener más información sobre cómo crear un par de AccessKey para un usuario de RAM, consulte Create an AccessKey pair. El AccessKey ID y el AccessKey Secret de un usuario de RAM solo se muestran cuando se crea el par de AccessKey. Debe guardarlos de inmediato. Si olvida el par de AccessKey, cree uno nuevo para realizar la rotación.

Variables de entorno

  1. Utilice el par de AccessKey de un usuario de RAM para configurar las variables de entorno.

    Linux

    1. Ejecute los siguientes comandos en la CLI para agregar la configuración de las variables de entorno al archivo ~/.bashrc:

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Aplique los cambios.

        source ~/.bashrc
      2. Compruebe si las variables de entorno han surtido efecto:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Ejecute el siguiente comando en la terminal para ver el tipo de shell predeterminado:

      echo $SHELL
      1. Configure las variables de entorno según el tipo de shell predeterminado.

        Zsh

        1. Ejecute los siguientes comandos para agregar la configuración de las variables de entorno al archivo ~/.zshrc:

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Aplique los cambios.

          source ~/.zshrc
        3. Compruebe si las variables de entorno han surtido efecto:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Ejecute los siguientes comandos para agregar la configuración de las variables de entorno al archivo ~/.bash_profile:

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
        2. Aplique los cambios.

          source ~/.bash_profile
        3. Compruebe si las variables de entorno han surtido efecto:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Ejecute los siguientes comandos en CMD:

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Compruebe si las variables de entorno han surtido efecto:

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Ejecute los siguientes comandos en PowerShell:

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
      1. Compruebe si la variable de entorno ha surtido efecto:

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Reinicie su entorno de desarrollo (IDE, terminales, servicios de backend) después de modificar las variables de entorno para cargar los nuevos valores.

  3. Utilice variables de entorno para pasar la información de las credenciales.

    <?php
    
    // Include the autoload file to ensure that dependencies are correctly loaded.
    require_once __DIR__ . '/../vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    
    $region = "<region-id>";
    
    // Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
    $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
    
    // Use the default SDK configurations.
    $cfg = Oss\Config::loadDefault();
    $cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
    $cfg->setRegion($region); // Set the bucket's region.
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations...

Credenciales estáticas

El siguiente código de ejemplo muestra cómo codificar las credenciales de acceso estableciendo explícitamente el par de AccessKey que se utilizará.

Aviso

No inserte credenciales de acceso en aplicaciones dentro de un entorno de producción. Este método es únicamente para fines de prueba.

<?php

// Include the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

$region = "<region-id>";

# Create a static credential provider and set your RAM user's AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\StaticCredentialsProvider("RAM AccessKey ID","RAM AccessKey Secret");

// Use the default SDK configurations.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the bucket's region.

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

// Use the created client for subsequent operations...

Uso de un token de STS

Si su aplicación requiere acceso temporal a OSS, puede inicializar el proveedor de credenciales con las credenciales de identidad temporales (AccessKey ID, AccessKey secret y token de Security Token Service (STS)) obtenidas desde STS. Tenga en cuenta que este método exige mantener manualmente el token de STS, lo cual incrementa los riesgos de seguridad y la complejidad de mantenimiento. Además, si necesita acceder a OSS de forma temporal en varias ocasiones, deberá actualizar manualmente el token de STS.

Importante
  • Para obtener rápidamente un token de STS mediante OpenAPI, consulte AssumeRole.

  • Para obtener un token de STS mediante un SDK, consulte Use an STS token to access OSS.

  • Tenga en cuenta que un token de STS tiene una fecha de caducidad que se define al generarlo. Una vez vencido, el token deja de ser válido y no puede utilizarse.

  • Para consultar la lista de endpoints del servicio STS, consulte Endpoints.

Variables de entorno

  1. Establezca las variables de entorno con las credenciales de identidad temporales.

    Mac OS X/Linux/Unix

    Aviso
    • Utilice las credenciales de identidad temporales (AccessKey ID, AccessKey secret y token de STS) obtenidas desde STS. No use el par de AccessKey de un usuario de RAM.

    • Tenga en cuenta que el AccessKey ID obtenido de STS comienza con "STS"; por ejemplo, "STS.".

    export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

    Windows

    Aviso
    • Utilice las credenciales de identidad temporales (AccessKey ID, AccessKey secret y token de STS) obtenidas desde STS. No use el par de AccessKey de un usuario de RAM.

    • Tenga en cuenta que el AccessKey ID obtenido de STS comienza con "STS"; por ejemplo, "STS.".

    set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
  2. Pase la información de credenciales mediante variables de entorno.

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once __DIR__ . '/../vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    
    $region = "<region-id>";
    
    // Use EnvironmentVariableCredentialsProvider to read the AccessKey ID, AccessKey secret, and security token from environment variables.
    $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
    
    // Use the default SDK configuration.
    $cfg = Oss\Config::loadDefault();
    $cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
    $cfg->setRegion($region); // Set the region where the bucket is located.
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations...

Credenciales estáticas

Puede insertar las credenciales directamente en su aplicación si establece explícitamente el par de AccessKey temporal que desea utilizar.

Aviso

No incruste credenciales de acceso en aplicaciones dentro de un entorno de producción. Este método está diseñado únicamente para fines de prueba.

<?php

// Import the autoload file to ensure that dependencies are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

$region = "<region-id>";

# Specify your temporary AccessKey ID and AccessKey secret. Do not use the AccessKey pair of your Alibaba Cloud account.
# The AccessKey ID from STS starts with "STS.".
$stsAccessKeyId = 'STS.****************';
$stsAccessKeySecret = 'yourAccessKeySecret';
# Specify your security token.
$stsSecurityToken = 'yourSecurityToken';

# Create a static credential provider and explicitly set the temporary AccessKey ID, AccessKey secret, and security token.
$credentialsProvider = new Oss\Credentials\StaticCredentialsProvider($stsAccessKeyId, $stsAccessKeySecret, $stsSecurityToken);

// Use the default SDK configuration.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.

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

// Use the created client for subsequent operations...

Uso de un ARN de rol de RAM

Para el acceso entre cuentas o la autorización delegada, inicialice el proveedor de credenciales con un ARN de rol de RAM. La herramienta Credentials obtiene y actualiza automáticamente los tokens de STS al llamar a AssumeRole. De manera opcional, puede asignar un parámetro policy para restringir los permisos del rol.

Importante
  • Una cuenta de Alibaba Cloud tiene permisos completos sobre todos los recursos. La filtración de un par de AccessKey representa riesgos de seguridad significativos. Utilice el par de AccessKey de un usuario de RAM con los permisos mínimos necesarios.

  • Para obtener más información sobre cómo crear un par de AccessKey para un usuario de RAM, consulte Create an AccessKey pair. El AccessKey ID y el AccessKey secret de un usuario de RAM solo se muestran cuando se crea el par de AccessKey. Debe guardarlos de inmediato. Si olvida el par de AccessKey, cree uno nuevo para realizar la rotación.

  • Para obtener más información sobre cómo conseguir un ARN de rol de RAM, consulte CreateRole.

  1. Agregue la biblioteca de credenciales de Alibaba Cloud credentials-php.

    composer require alibabacloud/credentials
  2. Configure el par de AccessKey y el ARN de rol de RAM como credenciales de acceso.

    <?php
    
    // Include the autoload file to ensure that dependencies are loaded correctly.
    require_once __DIR__ . '/../vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    use AlibabaCloud\Credentials\Credential;
    
    // Create a configuration object to define the credential type and related information.
    $config = new Credential\Config([
        // Specify the credential type. In this example, the RAM role ARN type is used.
        'type' => 'ram_role_arn',
    
        // The AccessKey ID of the Alibaba Cloud account.
        'accessKeyId' => 'AccessKeyId',
    
        // The AccessKey secret of the Alibaba Cloud account.
        'accessKeySecret' => 'AccessKeySecret',
    
        // The ARN of the RAM role. Example: acs:ram::USER_Id:role/ROLE_NAME.
        'roleArn' => 'RoleArn',
    
        // The role session name, used to identify the session.
        'roleSessionName' => 'yourRoleSessionName',
    
        // Optional. The policy used to limit the permissions of the STS token.
        'policy' => 'Policy',
    ]);
    
    // Initialize a credential instance with the configuration object.
    $credential = new Credential($config);
    
    // Load the default SDK configuration.
    $cfg = Oss\Config::loadDefault();
    
    // Set the credential provider to dynamically generate credentials with a callback function.
    $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) {
        // Obtain the temporary credentials (STS token).
        $cred = $credential->getCredential();
    
        // Return a credential object containing the AccessKey ID, AccessKey secret, and security token.
        return new Oss\Credentials\Credentials(
            accessKeyId: $cred->getAccessKeyId(),       // The temporary AccessKey ID.
            accessKeySecret: $cred->getAccessKeySecret(),   // The temporary AccessKey secret.
            securityToken: $cred->getSecurityToken()      // The security token (STS token).
        );
    }));
    
    $region = '<region-id>';
    $cfg->setRegion($region);
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the client for subsequent operations...

Uso de un rol de RAM de instancia

Para aplicaciones en instancias ECS, instancias ECI o nodos worker de Container Service for Kubernetes, utilice un rol de RAM de instancia. Este método actualiza automáticamente los tokens de STS dentro de su instancia de Container Service for Kubernetes sin necesidad de un par de AccessKey. CreateRole.

  1. Agregue la biblioteca de credenciales de Alibaba Cloud credentials-php.

    composer require alibabacloud/credentials
  2. Configure el rol de RAM de instancia como credencial de acceso.

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once 'vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    use AlibabaCloud\Credentials\Credential;
    
    // Create a configuration object for the credential type.
    $config = new Credential\Config([
        // Set the credential type. For an instance RAM role, this value must be 'ecs_ram_role'.
        'type' => 'ecs_ram_role',
    
        // The name of the RAM role attached to the instance.
        'roleName' => "<role_name>",  // Replace with your actual RAM role name.
    ]);
    
    // Initialize the credential instance.
    $credential = new Credential($config);
    
    // Load the default OSS configuration.
    $cfg = Oss\Config::loadDefault();
    
    // Set the credential provider to a function that dynamically generates credentials.
    $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) {
        // Get the temporary STS token.
        $cred = $credential->getCredential();
    
        // Return a new credential object with the AccessKey ID, AccessKey secret, and security token.
        return new Oss\Credentials\Credentials(
            accessKeyId: $cred->getAccessKeyId(),       // Temporary AccessKey ID
            accessKeySecret: $cred->getAccessKeySecret(), // Temporary AccessKey secret
            securityToken: $cred->getSecurityToken()   // Security token
        );
    }));
    
    $region = '<region-id>';
    $cfg->setRegion($region);
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations...
    

Uso de un ARN de rol OIDC

Para aplicaciones no confiables en pods de Container Service for Kubernetes (ACK) que no deben acceder al rol de RAM de instancia del nodo worker, utilice RAM Roles for Service Account (RRSA). ACK monta un archivo de token OIDC por pod e inyecta la configuración en las variables de entorno. La herramienta Credentials lee estas variables y llama a AssumeRoleWithOIDC para obtener un token de STS con permisos mínimos. No se requiere un par de AccessKey. Use RRSA to configure RAM permissions for a ServiceAccount and isolate pod permissions.

  1. Agregue la biblioteca de credenciales de Alibaba Cloud credentials-php.

    composer require alibabacloud/credentials
  1. Configure el ARN de rol OIDC como credencial de acceso.

    <?php
    
    // Load dependencies from the autoload file.
    require_once 'vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    use AlibabaCloud\Credentials\Credential;
    
    // Create a configuration object to define the credential type and related information.
    $config = new Credential\Config([
        // Specify the credential type. In this example, the oidc_role_arn type is used.
        'type' => 'oidc_role_arn',
    
        // Specify the ARN of the OIDC identity provider. You can also set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
        'oidcProviderArn' => '<oidc_provider_arn>',  // Replace with the actual OIDC identity provider ARN.
    
        // Specify the OIDC token file path. You can also set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
        'oidcTokenFilePath' => '<oidc_token_file_path>',  // Replace with the actual OIDC token file path.
    
        // Specify the ARN of the RAM role. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
        'roleArn' => '<role_arn>',  // Replace with the actual RAM role ARN.
    
        // Specify the role session name. You can also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        'roleSessionName' => '<role_session_name>',  // Replace with the actual role session name.
    
        // Optional: Specify a permission policy to further restrict the RAM role's permissions.
        // Example policy: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        'policy' => '',  // To limit permissions, replace this with the actual policy JSON string.
    
        // Optional: Specify the session validity period in seconds. The default value is 3,600 seconds.
        'roleSessionExpiration' => 3600,  // To adjust the validity period, modify this value.
    ]);
    
    // Initialize a credential instance using the configuration object.
    $credential = new Credential($config);
    
    // Load the default configurations and obtain the OSS configuration object.
    $cfg = Oss\Config::loadDefault();
    
    // Set a credential provider that uses a callback function to dynamically generate credentials.
    $cfg->setCredentialsProvider(new Oss\Credentials\CredentialsProviderFunc(function () use ($credential) {
        // Obtain the temporary credential (STS token).
        $cred = $credential->getCredential();
    
        // Return a credential object that contains the AccessKey ID, AccessKey secret, and security token.
        return new Oss\Credentials\Credentials(
            accessKeyId: $cred->getAccessKeyId(),       // The temporary AccessKey ID.
            accessKeySecret: $cred->getAccessKeySecret(), // The temporary AccessKey secret.
            securityToken: $cred->getSecurityToken()   // The security token (STS token).
        );
    }));
    
    $region = '<region-id>';
    $cfg->setRegion($region);
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations...

Uso de credenciales de acceso personalizadas

Si los métodos de configuración de credenciales anteriores no satisfacen sus necesidades, puede personalizar el método para obtener credenciales. El SDK admite varios métodos de implementación.

  1. Uso de Oss\Credentials\CredentialsProviderFunc

    Oss\Credentials\CredentialsProviderFunc es un contenedor de usabilidad para Oss\Credentials\CredentialsProvider.

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once 'vendor/autoload.php';
    
    // Import the necessary namespaces.
    use AlibabaCloud\Oss\V2 as Oss;
    use AlibabaCloud\Oss\V2\Credentials\Credentials;
    
    // Create a credential provider that dynamically generates a credential by using an anonymous function.
    $provider = new Oss\Credentials\CredentialsProviderFunc(
        function () {
            // Return a long-term credential, which contains only an AccessKey ID and an AccessKey secret.
            return new Credentials(
                accessKeyId: 'id',         // Replace with the actual RAM AccessKey ID.
                accessKeySecret: 'secret'  // Replace with the actual RAM AccessKey secret.
            );
    
            // To return a temporary credential, which includes a security token, uncomment the following code and replace the values.
            /*
            return new Credentials(
                accessKeyId: 'id',          // Replace with the actual STS temporary credential AccessKey ID.
                accessKeySecret: 'secret', // Replace with the actual STS temporary credential AccessKey secret.
                securityToken: 'token'     // Replace with the actual STS security token.
            );
            */
        }
    );
    
    // Load the default configuration and get the OSS configuration object.
    $cfg = Oss\Config::loadDefault();
    
    // Set the credential provider to the dynamically generated provider.
    $cfg->setCredentialsProvider($provider);
    
    $region = '<region-id>';
    $cfg->setRegion($region);
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations...
    
  2. Implementación de Oss\Credentials\CredentialsProvider

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once 'vendor/autoload.php';
    
    // Import the necessary namespaces.
    use AlibabaCloud\Oss\V2 as Oss;
    use AlibabaCloud\Oss\V2\Credentials\Credentials;
    
    // Custom credential provider class that implements the CredentialsProvider interface.
    class CustomerCredentialsProvider implements Oss\Credentials\CredentialsProvider
    {
        /**
         * Gets the credential object.
         *
         * @return Credentials Returns a credential object.
         */
        public function getCredentials(): Credentials
        {
            // Return a long-term credential, which contains only an AccessKey ID and an AccessKey secret.
            return new Credentials(
                accessKeyId: 'id',         // Replace with the actual RAM AccessKey ID.
                accessKeySecret: 'secret'  // Replace with the actual RAM AccessKey secret.
            );
    
            // To return a temporary credential, which includes a security token, uncomment the following code and replace the values.
            /*
            return new Credentials(
                accessKeyId: 'id',          // Replace with the actual STS temporary credential AccessKey ID.
                accessKeySecret: 'secret', // Replace with the actual STS temporary credential AccessKey secret.
                securityToken: 'token'     // Replace with the actual STS security token.
            );
            */
        }
    }
    
    // Instantiate the custom credential provider.
    $provider = new CustomerCredentialsProvider();
    
    // Load the default configuration and get the OSS configuration object.
    $cfg = Oss\Config::loadDefault();
    
    // Set the credential provider to the custom provider instance.
    $cfg->setCredentialsProvider($provider);
    
    $region = '<region-id>';
    $cfg->setRegion($region);
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Use the created client for subsequent operations...
    

Solución de errores

Cuando ocurre un error, OSS devuelve un código de estado HTTP, un mensaje, un ID de solicitud y un código de error (EC). Utilice el EC para diagnosticar el problema.

  1. Por ejemplo, si utiliza el siguiente código para descargar un archivo que no existe:

    <?php
    
    // Import the autoload file to ensure that dependencies are correctly loaded.
    require_once __DIR__ . '/../vendor/autoload.php';
    
    use AlibabaCloud\Oss\V2 as Oss;
    
    // Define the description for command-line arguments.
    $optsdesc = [
        "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located (required).
        "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint (optional).
        "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name (required).
        "key" => ['help' => 'The name of the object', 'required' => True], // The object name (required).
    ];
    
    // Convert the parameter descriptions to the long option format required by getopt.
    // A colon ":" after each parameter indicates that the parameter requires a value.
    $longopts = \array_map(function ($key) {
        return "$key:";
    }, array_keys($optsdesc));
    
    // Parse the command-line arguments.
    $options = getopt("", $longopts);
    
    // Verify that all required parameters are present.
    foreach ($optsdesc as $key => $value) {
        if ($value['required'] === True && empty($options[$key])) {
            $help = $value['help']; // Get the help information for the parameter.
            echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
            exit(1); // Exit the program if a required parameter is missing.
        }
    }
    
    // Extract values from the parsed parameters.
    $region = $options["region"]; // The region where the bucket is located.
    $bucket = $options["bucket"]; // The bucket name.
    $key = $options["key"];       // The object name.
    
    // Load credentials from environment variables.
    // Use EnvironmentVariableCredentialsProvider to read the AccessKey ID and AccessKey secret from environment variables.
    $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
    
    // Use the default SDK configurations.
    $cfg = Oss\Config::loadDefault();
    $cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
    $cfg->setRegion($region); // Set the region where the bucket is located.
    if (isset($options["endpoint"])) {
        $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
    }
    
    // Create an OSS client instance.
    $client = new Oss\Client($cfg);
    
    // Create a GetObjectRequest object to get the content of the specified object.
    $request = new Oss\Models\GetObjectRequest(bucket: $bucket, key: $key);
    
    // Perform the get object operation.
    $result = $client->getObject($request);
    
    // Define the local file path to save the content.
    $localFilePath = './test/file.txt'; // Replace with the actual file path.
    
    // Write the content to the local file.
    file_put_contents( $localFilePath, $result->body->getContents());
    
    // Print the result.
    // Output the HTTP status code, request ID, and object content.
    printf(
        'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates success.
        'request id:' . $result->requestId . PHP_EOL  // The request ID, used for debugging or tracking requests.
    );
    
  2. Ejemplo de respuesta de error. El valor 'EC': '0026-00000001' identifica la causa específica del error.

    teyimui@xxx 2051 get_object % php get_object_to_file.php   region cn-hangzhou   bucket xxx
    PHP Fatal error:  Uncaught AlibabaCloud\Oss\V2\Exception\ServiceException: Error returned by Service.
    Http Status Code: 404
    Error Code: NoSuchKey
    Request Id: 687F3B562C1E9331312B1F00
    Message: The specified key does not exist.
    EC: 0026-00000001
    Timestamp: Tue, 22 Jul 2025 07:18:46 GMT
    Request Endpoint: GET https://xxx.oss-cn-hangzhou.aliyuncs.com/put-php.txt in xxx
  3. Diagnostique el error mediante el EC de la respuesta:

    1. Abra el Centro de solución de problemas de OpenAPI.

    2. En el cuadro de búsqueda, introduzca el EC; por ejemplo, 0026-00000001. Haga clic en Diagnose.

    3. La página de resultados muestra la descripción del problema, la causa y la solución.

Código de ejemplo

A continuación se presenta una tabla con el código de ejemplo para las operaciones más comunes.

Contenido de ejemplo

Archivo de ejemplo en GitHub

Create a bucket (OSS SDK for PHP 2.0)

PutBucket.php

List buckets (OSS SDK for PHP 2.0)

ListBuckets.php

Check if a bucket exists (OSS SDK for PHP 2.0)

IsBucketExist.php

Get the region of a bucket (OSS SDK for PHP 2.0)

GetBucketLocation.php

Get bucket information (OSS SDK for PHP 2.0)

GetBucketInfo.php

Get the storage capacity of a bucket (OSS SDK for PHP 2.0)

GetBucketStat.php

Delete a bucket (OSS SDK for PHP 2.0)

DeleteBucket.php

Bucket tagging (OSS SDK for PHP 2.0)

Pay-by-requester (OSS SDK for PHP 2.0)

Simple upload (OSS SDK for PHP 2.0)

PutObject.php

Append upload (OSS SDK for PHP 2.0)

AppendObject.php

Multipart upload (OSS SDK for PHP 2.0)

CompleteMultipartUpload.php

Form upload (OSS SDK for PHP 2.0)

PostObject.php

Upload an object using a signed URL (OSS SDK for PHP 2.0)

Presign.php

File upload manager (OSS SDK for PHP 2.0)

Uploader.php

Simple download (OSS SDK for PHP 2.0)

GetObject.php

Range download (OSS SDK for PHP 2.0)

GetObject.php

Download an object using a signed URL (OSS SDK for PHP 2.0)

Presign.php

File download manager (OSS SDK for PHP 2.0)

Downloader.php

Copy an object (OSS SDK for PHP 2.0)

CopyObject.php

Multipart copy (OSS SDK for PHP 2.0)

UploadPartCopy.php

File copy manager (OSS SDK for PHP 2.0)

Copier.php

Check if an object exists (OSS SDK for PHP 2.0)

IsObjectExist.php

List objects (OSS SDK for PHP 2.0)

ListObjectsV2.php

Delete objects (OSS SDK for PHP 2.0)

DeleteObject.php

Restore a file

RestoreObject.php

Manage object metadata (OSS SDK for PHP 2.0)

HeadObject.php

Convert object storage classes (OSS SDK for PHP 2.0)

CopyObject.php

Rename a file (OSS SDK for PHP 2.0)

CopyObject.php

Manage symbolic links (OSS SDK for PHP 2.0)

Set object tags (OSS SDK for PHP 2.0)

Get object tags (OSS SDK for PHP 2.0)

Delete object tags (OSS SDK for PHP 2.0)

Manage bucket ACLs (OSS SDK for PHP 2.0)

Manage object ACLs (OSS SDK for PHP 2.0)

Bucket policies (OSS SDK for PHP 2.0)

Manage versioning (OSS SDK for PHP 2.0)

Hotlink protection (OSS SDK for PHP 2.0)

Cross-origin resource sharing (OSS SDK for PHP 2.0)

Retention policies (OSS SDK for PHP 2.0)

Server-side encryption (OSS SDK for PHP 2.0)

Client-side encryption (OSS SDK for PHP 2.0)

EncryptionClient.php

Data replication (OSS SDK for PHP 2.0)

Access tracking (OSS SDK for PHP 2.0)

Lifecycle management (OSS SDK for PHP 2.0)

Static website hosting (OSS SDK for PHP 2.0)

Log storage (OSS SDK for PHP 2.0)

Real-time access of Archive objects (OSS SDK for PHP 2.0)

PutBucketArchiveDirectRead.php

Scalar search (OSS SDK for PHP 2.0)

Vector search (OSS SDK for PHP 2.0)

Bind a custom domain name (OSS SDK for PHP 2.0)

Transfer acceleration (OSS SDK for PHP 2.0)

Synchronous processing (OSS SDK for PHP 2.0)

ProcessObject.php

Asynchronous processing (OSS SDK for PHP 2.0)

AsyncProcessObject.php

Global Block Public Access (OSS SDK for PHP 2.0)

PutPublicAccessBlock.php

Bucket-level Block Public Access (OSS SDK for PHP 2.0)

PutBucketPublicAccessBlock.php