Todos os produtos
Search
Central de documentação

Object Storage Service:OSS SDK for PHP 2.0

Última atualização: Aug 03, 2026

GitHub | Guia do desenvolvedor do OSS SDK for PHP 2.0 | Versões do SDK

Integração rápida

image

Pré-requisitos

O OSS SDK for PHP 2.0 oferece suporte ao PHP 7.4 ou posterior. Os exemplos de código neste documento usam argumentos nomeados do PHP 8 e, portanto, exigem o PHP 8,0 ou superior. Baixe o Composer para gerenciar pacotes.

Execute o comando php -version para verificar a versão do PHP. Se o PHP não estiver instalado ou a versão for anterior à 8,0, baixe e instale o PHP .

Instalar o SDK

  1. Crie um diretório de projeto e execute o comando a seguir para instalar o OSS SDK for PHP 2.0 via Composer. Use a versão mais recente para garantir a compatibilidade dos exemplos de código.

    mkdir oss-php-example && cd oss-php-example && composer require alibabacloud/oss-v2
  2. Importe o pacote do OSS SDK for PHP 2.0:

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

Configurar credenciais de acesso

Configure as credenciais de acesso usando o par de AccessKey de um usuário RAM.

  1. No console do RAM, crie um usuário RAM com um AccessKey Pair permanente. Salve o par de AccessKey e conceda a permissão AliyunOSSFullAccess ao usuário RAM.

  2. Use o par de AccessKey do usuário RAM para configurar as variáveis de ambiente.

    Linux

    1. Execute os comandos a seguir para adicionar as configurações das variáveis de ambiente ao arquivo ~/.bashrc .

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Execute o comando a seguir para aplicar as alterações.

        source ~/.bashrc
      2. Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas corretamente.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Execute o comando a seguir no terminal para visualizar o tipo de shell padrão.

      echo $SHELL
      1. Siga as etapas abaixo conforme o tipo de shell padrão.

        Zsh

        1. Execute os comandos a seguir para adicionar as configurações das variáveis de ambiente ao arquivo ~/.zshrc.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Execute o comando a seguir para aplicar as alterações.

          source ~/.zshrc
        3. Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas corretamente.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Execute os comandos a seguir para adicionar as configurações das variáveis de ambiente ao arquivo ~/.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. Execute o comando a seguir para aplicar as alterações.

          source ~/.bash_profile
        3. Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas corretamente.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Execute os comandos a seguir na janela do Prompt de Comando.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas corretamente.

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Execute os comandos a seguir no 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. Execute os comandos a seguir para verificar se as variáveis de ambiente foram configuradas corretamente.

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

Inicializar o cliente

Importante

Devido a uma alteração de política para melhorar a conformidade e a segurança, a partir de 20 de março de 2025, novos usuários do OSS devem usar um nome de domínio personalizado (CNAME) para executar operações de API de dados em buckets do OSS localizados em regiões da China continental. Os endpoints públicos padrão estão restritos para essas operações. Consulte o anúncio oficial para obter a lista completa das operações afetadas. Se você acessar seus dados via HTTPS, deverá vincular um certificado SSL válido ao seu domínio personalizado. Isso é obrigatório para acesso ao Console do OSS, pois o console impõe o uso de HTTPS.

Antes de executar o código de exemplo, substitua os espaços reservados, como <region-id> , pela sua região e endpoint reais, como 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
);

Saída esperada após um upload bem-sucedido:

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

Configurações do cliente

Quais são as configurações de cliente suportadas?

Parâmetro

Descrição

Exemplo

region

(Obrigatório) A região de destino para as requisições.

setRegion("<region-id>")

credentialsProvider

(Obrigatório) O provedor de credenciais de acesso.

setCredentialsProvider(provider)

endpoint

O endpoint.

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

retryMaxAttempts

O número máximo de tentativas para uma requisição HTTP. O valor padrão é 3.

setRetryMaxAttempts(5)

retryer

A implementação de nova tentativa para uma requisição HTTP.

setRetryer(customRetryer)

connectTimeout

O tempo limite para estabelecer uma conexão. O valor padrão é 10 segundos.

setConnectTimeout(5)

readWriteTimeout

O tempo limite para leitura e gravação de dados. O valor padrão é 20 segundos.

setReadwriteTimeout(30)

insecureSkipVerify

Define se a verificação do certificado SSL deve ser ignorada. Por padrão, os certificados SSL são verificados.

setInsecureSkipVerify(true)

enabledRedirect

Define se o redirecionamento HTTP deve ser ativado. Por padrão, esse recurso está desativado.

setEnabledRedirect(true)

proxyHost

Configurar um servidor proxy

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

signatureVersion

A versão da assinatura. O valor padrão é v4.

setSignatureVersion("v1")

disableSSL

Define se requisições HTTPS devem ser usadas. Por padrão, o HTTPS é usado.

setDisableSSL(true)

usePathStyle

Define se URLs no estilo de caminho devem ser usadas. Por padrão, URLs no estilo de host virtual são usadas.

setUsePathStyle(true)

useCName

Define se um nome de domínio personalizado deve ser usado. Por padrão, nomes de domínio personalizados não são usados.

setUseCName(true)

useDualStackEndpoint

Define se um endpoint de pilha dupla deve ser usado. Por padrão, endpoints de pilha dupla não são usados.

setUseDualStackEndpoint(true)

useAccelerateEndpoint

Define se um endpoint de aceleração deve ser usado. Por padrão, endpoints de aceleração não são usados.

setUseAccelerateEndpoint(true)

useInternalEndpoint

Define se um endpoint interno deve ser usado. Por padrão, endpoints internos não são usados.

setUseInternalEndpoint(true)

additionalHeaders

Os cabeçalhos adicionais da requisição a serem assinados. Este parâmetro é válido apenas para assinaturas V4.

setAdditionalHeaders(['content-length'])

userAgent

As informações adicionais do User-Agent.

setUserAgent('user identifier')

Usar um nome de domínio personalizado

Para ativar a pré-visualização de arquivos no navegador e a aceleração via CDN, vincule um nome de domínio personalizado ao seu 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...

Controle de tempo limite

<?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 tentativas

Por padrão, o OSSClient tenta novamente requisições falhas 3 vezes.

Em cenários de alta concorrência ou redes instáveis, aumente o número de tentativas com 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

Use setDisableSSL(true) para desativar o 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.

Usar corrotinas no framework Swoole

O código a seguir demonstra como criar um cliente OSS com suporte a corrotinas baseado no 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.
    }
});

Usar um endpoint interno

Se sua aplicação estiver implantada em uma instância ECS da Alibaba Cloud e precisar acessar frequentemente recursos do OSS na mesma região, use um endpoint interno para reduzir custos de tráfego e aumentar a velocidade de acesso.

<?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...

Usar um endpoint de aceleração

<?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.

Usar um domínio 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...

Usar um endpoint da Alibaba Gov Cloud

O código a seguir fornece um exemplo de como configurar o OSSClient usando um endpoint da 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.

Configurações de credenciais de acesso

Selecione um método de credencial com base nos seus requisitos de autenticação.

Como selecionar as credenciais de acesso?

Método de inicialização do provedor de credenciais

Cenários

Requer um par de AccessKey ou token STS pré-existente

Credencial subjacente

Período de validade da credencial

Método de rotação ou atualização da credencial

Usar o par de AccessKey de um usuário RAM

Aplicações implantadas em um ambiente seguro e estável, não suscetíveis a ataques externos. Essas aplicações requerem acesso de longo prazo aos serviços da Alibaba Cloud sem rotação frequente de credenciais.

Sim

Par de AccessKey

Longo prazo

Rotação manual

Usar um token STS

Aplicações implantadas em um ambiente não confiável. Você deseja controlar o período de validade e as permissões de acesso.

Sim

Token STS

Temporário

Atualização manual

Usar um ARN de função RAM

Aplicações que requerem acesso autorizado aos serviços da Alibaba Cloud, como acesso entre contas.

Sim

Token STS

Temporário

Atualização automática

Usar uma função RAM de instância

Aplicações implantadas em instâncias ECS da Alibaba Cloud, instâncias ECI ou nós de trabalho do Container Service for Kubernetes.

Não

Token STS

Temporário

Atualização automática

Usar um ARN de função OIDC

Aplicações não confiáveis implantadas em nós de trabalho do Container Service for Kubernetes.

Não

Token STS

Temporário

Atualização automática

Provedor de credenciais personalizado

Se nenhum dos métodos anteriores atender aos seus requisitos, personalize o método para obter credenciais.

Personalizado

Personalizado

Personalizado

Personalizado

Usar o par de AccessKey de um usuário RAM

Inicialize o provedor de credenciais com o par de AccessKey de uma conta Alibaba Cloud ou de um usuário RAM. Adequado para ambientes seguros que exigem acesso de longo prazo ao OSS sem rotação frequente de credenciais. Este método requer manutenção manual do AccessKey, o que aumenta os riscos de segurança.

Aviso
  • Uma conta Alibaba Cloud possui permissões totais sobre todos os recursos. O vazamento do par de AccessKey representa riscos significativos de segurança. Use o par de AccessKey de um usuário RAM com as permissões mínimas necessárias.

  • Para mais informações sobre como criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey. O AccessKey ID e o AccessKey Secret de um usuário RAM são exibidos apenas no momento da criação do par. Salve-os imediatamente. Caso esqueça o par de AccessKey, crie um novo para realizar a rotação.

Variáveis de ambiente

  1. Use o par de AccessKey de um usuário RAM para configurar as variáveis de ambiente.

    Linux

    1. Execute os comandos a seguir na CLI para adicionar as configurações das variáveis de ambiente ao arquivo ~/.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 as alterações.

        source ~/.bashrc
      2. Verifique se as variáveis de ambiente entraram em vigor:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Execute o comando a seguir no terminal para visualizar o tipo de shell padrão:

      echo $SHELL
      1. Configure as variáveis de ambiente conforme o tipo de shell padrão.

        Zsh

        1. Execute os comandos a seguir para adicionar as configurações das variáveis de ambiente ao arquivo ~/.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 as alterações.

          source ~/.zshrc
        3. Verifique se as variáveis de ambiente entraram em vigor:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Execute os comandos a seguir para adicionar as configurações das variáveis de ambiente ao arquivo ~/.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 as alterações.

          source ~/.bash_profile
        3. Verifique se as variáveis de ambiente entraram em vigor:

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Execute os comandos a seguir no CMD:

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Verifique se as variáveis de ambiente entraram em vigor:

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Execute os comandos a seguir no 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. Verifique se a variável de ambiente entrou em vigor:

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Reinicie seu ambiente de desenvolvimento (IDEs, terminais, serviços de backend) após modificar as variáveis de ambiente para carregar os novos valores.

  3. Use variáveis de ambiente para passar as informações de credencial.

    <?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...

Credenciais estáticas

O código de exemplo a seguir mostra como codificar as credenciais de acesso definindo explicitamente o par de AccessKey a ser usado.

Aviso

Não incorpore credenciais de acesso em aplicações em ambiente de produção. Este método destina-se apenas a testes.

<?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...

Usar um token STS

Se sua aplicação exigir acesso temporário ao OSS, inicialize o provedor de credenciais usando as credenciais de identidade temporárias (AccessKey ID, AccessKey Secret e token do Security Token Service (STS)) obtidas via STS. Note que este método exige a manutenção manual de um token STS, o que aumenta os riscos de segurança e a complexidade de manutenção. Além disso, se você precisar acessar o OSS temporariamente várias vezes, deverá atualizar manualmente o token STS.

Importante
  • Para obter rapidamente um token STS usando a OpenAPI, consulte AssumeRole.

  • Para obter um token STS usando um SDK, consulte Usar um token STS para acessar o OSS.

  • Observe que um token STS possui um tempo de expiração definido no momento de sua geração. Após expirar, ele se torna inválido e não pode ser usado.

  • Para obter uma lista de endpoints do serviço STS, consulte Endpoints.

Variáveis de ambiente

  1. Defina as variáveis de ambiente usando credenciais de identidade temporárias.

    Mac OS X/Linux/Unix

    Aviso
    • Use as credenciais de identidade temporárias (AccessKey ID, AccessKey Secret e token STS) obtidas via STS. Não use o par de AccessKey de um usuário RAM.

    • Note que o AccessKey ID obtido via STS começa com "STS", por exemplo, "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
    • Use as credenciais de identidade temporárias (AccessKey ID, AccessKey Secret e token STS) obtidas via STS. Não use o par de AccessKey de um usuário RAM.

    • Note que o AccessKey ID obtido via STS começa com "STS", por exemplo, "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. Passe as informações de credencial usando variáveis de ambiente.

    <?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...

Credenciais estáticas

É possível codificar as credenciais na sua aplicação definindo explicitamente o par de AccessKey temporário a ser usado.

Aviso

Não incorpore credenciais de acesso em aplicações em ambiente de produção. Este método destina-se apenas a testes.

<?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...

Usar um ARN de função RAM

Para acesso entre contas ou autorização delegada, inicialize o provedor de credenciais com um ARN de função RAM. A ferramenta Credentials obtém e atualiza automaticamente os tokens STS chamando AssumeRole. Opcionalmente, atribua um parâmetro policy para restringir as permissões da função.

Importante
  • Uma conta Alibaba Cloud possui permissões totais sobre todos os recursos. O vazamento do par de AccessKey representa riscos significativos de segurança. Use o par de AccessKey de um usuário RAM com as permissões mínimas necessárias.

  • Para mais informações sobre como criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey. O AccessKey ID e o AccessKey Secret de um usuário RAM são exibidos apenas no momento da criação do par. Salve-os imediatamente. Caso esqueça o par de AccessKey, crie um novo para realizar a rotação.

  • Para mais informações sobre como obter um ARN de função RAM, consulte CreateRole.

  1. Adicione a biblioteca de credenciais da Alibaba Cloud credentials-php.

    composer require alibabacloud/credentials
  2. Configure o par de AccessKey e o ARN da função RAM como credenciais de acesso.

    <?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...

Usar uma função RAM de instância

Para aplicações em instâncias ECS, instâncias ECI ou nós de trabalho do Container Service for Kubernetes, use uma função RAM de instância. Este método atualiza automaticamente os tokens STS dentro da sua instância Container Service for Kubernetes sem exigir um par de AccessKey. CreateRole.

  1. Adicione a biblioteca de credenciais da Alibaba Cloud credentials-php.

    composer require alibabacloud/credentials
  2. Configure a função RAM da instância como credencial de acesso.

    <?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...
    

Usar um ARN de função OIDC

Para aplicações não confiáveis em pods do Container Service for Kubernetes (ACK) que não devem acessar a função RAM da instância do nó de trabalho, use RAM Roles for Service Account (RRSA). O ACK monta um arquivo de token OIDC por pod e injeta a configuração nas variáveis de ambiente. A ferramenta Credentials lê essas variáveis e chama AssumeRoleWithOIDC para obter um token STS com permissões mínimas. Nenhum par de AccessKey é necessário. Usar RRSA para configurar permissões RAM para uma ServiceAccount e isolar permissões de pod.

  1. Adicione a biblioteca de credenciais da Alibaba Cloud credentials-php.

    composer require alibabacloud/credentials
  1. Configure o ARN da função OIDC como credencial de acesso.

    <?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...

Usar credenciais de acesso personalizadas

Se os métodos de configuração de credenciais anteriores não atenderem aos seus requisitos, personalize o método para obter credenciais. O SDK suporta múltiplos métodos de implementação.

  1. Usar Oss\Credentials\CredentialsProviderFunc

    Oss\Credentials\CredentialsProviderFunc é um wrapper de usabilidade 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. Implementar 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...
    

Solucionar erros

Quando ocorre um erro, o OSS retorna um código de status HTTP, mensagem, ID da requisição e código de erro (EC). Use o EC para diagnosticar o problema.

  1. Por exemplo, você usa o código a seguir para baixar um arquivo que não 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. Exemplo de resposta de erro. O 'EC': '0026-00000001' identifica a causa específica do erro.

    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 o erro usando o EC da resposta:

    1. Abra a Central de Solução de Problemas da OpenAPI.

    2. Na caixa de pesquisa, insira o EC, por exemplo, 0026-00000001. Clique em Diagnose.

    3. A página de resultados exibe a descrição do problema, a causa e a solução.

Código de exemplo

A tabela a seguir lista códigos de exemplo para operações comuns.

Conteúdo do exemplo

Arquivo de exemplo no GitHub

Criar um bucket (OSS SDK for PHP 2.0)

PutBucket.php

Listar buckets (OSS SDK for PHP 2.0)

ListBuckets.php

Verificar se um bucket existe (OSS SDK for PHP 2.0)

IsBucketExist.php

Obter a região de um bucket (OSS SDK for PHP 2.0)

GetBucketLocation.php

Obter informações do bucket (OSS SDK for PHP 2.0)

GetBucketInfo.php

Obter a capacidade de armazenamento de um bucket (OSS SDK for PHP 2.0)

GetBucketStat.php

Excluir um bucket (OSS SDK for PHP 2.0)

DeleteBucket.php

Tags de bucket (OSS SDK for PHP 2.0)

Pagamento pelo solicitante (OSS SDK for PHP 2.0)

Upload simples (OSS SDK for PHP 2.0)

PutObject.php

Upload por anexação (OSS SDK for PHP 2.0)

AppendObject.php

Upload multipart (OSS SDK for PHP 2.0)

CompleteMultipartUpload.php

Upload de formulário (OSS SDK for PHP 2.0)

PostObject.php

Fazer upload de um objeto usando uma URL assinada (OSS SDK for PHP 2.0)

Presign.php

Gerenciador de upload de arquivos (OSS SDK for PHP 2.0)

Uploader.php

Download simples (OSS SDK for PHP 2.0)

GetObject.php

Download por intervalo (OSS SDK for PHP 2.0)

GetObject.php

Baixar um objeto usando uma URL assinada (OSS SDK for PHP 2.0)

Presign.php

Gerenciador de download de arquivos (OSS SDK for PHP 2.0)

Downloader.php

Copiar um objeto (OSS SDK for PHP 2.0)

CopyObject.php

Cópia multipart (OSS SDK for PHP 2.0)

UploadPartCopy.php

Gerenciador de cópia de arquivos (OSS SDK for PHP 2.0)

Copier.php

Verificar se um objeto existe (OSS SDK for PHP 2.0)

IsObjectExist.php

Listar objetos (OSS SDK for PHP 2.0)

ListObjectsV2.php

Excluir objetos (OSS SDK for PHP 2.0)

DeleteObject.php

Restaurar um arquivo

RestoreObject.php

Gerenciar metadados de objetos (OSS SDK for PHP 2.0)

HeadObject.php

Converter classes de armazenamento de objetos (OSS SDK for PHP 2.0)

CopyObject.php

Renomear um arquivo (OSS SDK for PHP 2.0)

CopyObject.php

Gerenciar links simbólicos (OSS SDK for PHP 2.0)

Definir tags de objetos (OSS SDK for PHP 2.0)

Obter tags de objetos (OSS SDK for PHP 2.0)

Excluir tags de objetos (OSS SDK for PHP 2.0)

Gerenciar ACLs de bucket (OSS SDK for PHP 2.0)

Gerenciar ACLs de objetos (OSS SDK for PHP 2.0)

Políticas de bucket (OSS SDK for PHP 2.0)

Gerenciar versionamento (OSS SDK for PHP 2.0)

Proteção contra hotlink (OSS SDK for PHP 2.0)

Compartilhamento de recursos de origem cruzada (OSS SDK for PHP 2.0)

Políticas de retenção (OSS SDK for PHP 2.0)

Criptografia no lado do servidor (OSS SDK for PHP 2.0)

Criptografia no lado do cliente (OSS SDK for PHP 2.0)

EncryptionClient.php

Replicação de dados (OSS SDK for PHP 2.0)

Rastreamento de acesso (OSS SDK for PHP 2.0)

Gerenciamento de ciclo de vida (OSS SDK for PHP 2.0)

Hospedagem de site estático (OSS SDK for PHP 2.0)

Armazenamento de logs (OSS SDK for PHP 2.0)

Acesso em tempo real a objetos Archive (OSS SDK for PHP 2.0)

PutBucketArchiveDirectRead.php

Pesquisa escalar (OSS SDK for PHP 2.0)

Pesquisa vetorial (OSS SDK for PHP 2.0)

Vincular um nome de domínio personalizado (OSS SDK for PHP 2.0)

Aceleração de transferência (OSS SDK for PHP 2.0)

Processamento síncrono (OSS SDK for PHP 2.0)

ProcessObject.php

Processamento assíncrono (OSS SDK for PHP 2.0)

AsyncProcessObject.php

Bloqueio global de acesso público (OSS SDK for PHP 2.0)

PutPublicAccessBlock.php

Bloqueio de acesso público no nível do bucket (OSS SDK for PHP 2.0)

PutBucketPublicAccessBlock.php