Todos os produtos
Search
Central de documentação

Object Storage Service:Restaurar objetos usando o OSS SDK for PHP 2.0

Última atualização: Jul 03, 2026

É necessário restaurar objetos Archive, Cold Archive e Deep Cold Archive antes de lê-los. A restauração gera uma réplica temporária que coexiste com o objeto original. Após o término do período de restauração, o sistema exclui essa réplica automaticamente.

Observações

  • A operação RestoreObject aplica-se apenas a objetos Archive, Cold Archive e Deep Cold Archive.

  • O código de exemplo neste tópico usa o ID da região cn-hangzhou, correspondente à região China (Hangzhou), e acessa recursos por um endpoint público por padrão. Para acessar recursos de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints compatíveis, consulte Regiões e endpoints.

  • Restaurar objetos exige a permissão oss:RestoreObject. Para obter mais informações, consulte Conceder uma política personalizada.

Código de exemplo

O código de exemplo a seguir mostra como restaurar objetos Archive, Cold Archive ou Deep Cold Archive.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define and describe command-line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint for accessing OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];

// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"];       // The name of the object.

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

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

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

// Create a RestoreObjectRequest object to restore the Archive object.
$request = new Oss\Models\RestoreObjectRequest(bucket: $bucket, key: $key);

// Restore the object.
$result = $client->restoreObject($request);

// Display the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request succeeded.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which can be used to debug or trace the request.
);

Cenários comuns

Excluir uma réplica Standard usando o método CleanRestoredObject

A restauração de um objeto Cold Archive ou Deep Cold Archive no OSS gera uma réplica Standard para acesso temporário. O armazenamento temporário dessa réplica gera custos até que o objeto retorne ao estado congelado. Para remover o objeto do estado restaurado antecipadamente e interromper a cobrança de armazenamento da réplica, envie uma solicitação CleanRestoredObject. Após a conclusão da solicitação, o objeto retorna ao estado congelado e não pode ser lido diretamente.

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define and describe command-line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint for accessing OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];

// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"];       // The name of the object.

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

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

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

// Create a CleanRestoredObjectRequest object to clean up the restored Archive objects.
$request = new Oss\Models\CleanRestoredObjectRequest($bucket, $key);

// Execute the request.
$result = $client->cleanRestoredObject($request);

// Display the result of the request.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which can be used to debug or trace the request.
);

Referências

  • Para obter o código de exemplo completo de restauração de objetos, visite o GitHub.

  • Para obter mais informações sobre a operação de API RestoreObject, consulte RestoreObject.

  • Para obter mais informações sobre a restauração de objetos, consulte Restaurar objetos.