Todos os produtos
Search
Central de documentação

Object Storage Service:Conditional download (PHP SDK V1)

Última atualização: Sep 22, 2026

Baixe um objeto do Object Storage Service (OSS) apenas quando os critérios definidos forem atendidos. Para isso, especifique uma ou mais condições antes de iniciar a transferência. Se os requisitos não forem cumpridos, a API retorna um erro e a operação é cancelada.

Notas de uso

  • Neste tópico, utilizamos o endpoint público da região China (Hangzhou). Para acessar o OSS por meio de outros serviços do Alibaba Cloud na mesma região, utilize um endpoint interno. Consulte Regions and endpoints para ver a lista completa de regiões e endpoints compatíveis.

  • Crie uma instância de OSSClient utilizando o endpoint do OSS, conforme demonstrado aqui. Para configurações alternativas, como domínios personalizados ou autenticação via Security Token Service (STS), consulte Create an OssClient.

  • Execute transferências condicionais apenas se sua conta possuir a permissão oss:GetObject concedida. Para detalhes sobre políticas de acesso, consulte Attach a custom policy to a RAM user.

Condições

A tabela a seguir detalha os critérios suportados pelo OSS. É possível combinar If-Modified-Since e If-Unmodified-Since na mesma requisição, assim como If-Match e If-None-Match.

Parâmetro

Descrição

Método

If-Modified-Since

Baixe o arquivo se ele for modificado após o horário informado. Caso contrário, a API retorna um erro 304 Not modified.

OssClient::OSS_IF_MODIFIED_SINCE

If-Unmodified-Since

Baixe o arquivo quando a modificação ocorrer no momento ou antes do horário especificado. Caso contrário, um erro 412 Precondition failed é retornado.

OssClient::OSS_IF_UNMODIFIED_SINCE

If-Match

Baixe o arquivo se o ETag do objeto no OSS corresponder ao valor indicado. Caso haja divergência, a operação falha com um erro 412 Precondition failed.

Nota

Recupere o ETag de um objeto usando o método $ossClient->getObjectMeta.

OssClient::OSS_IF_MATCH

If-None-Match

Baixe o arquivo quando o ETag do objeto no OSS diferir do valor informado. Se os valores coincidirem, a API retorna um erro 304 Not modified.

OssClient::OSS_IF_NONE_MATCH

Baixe um objeto para a memória local de forma condicional

Especifique as condições para baixe um objeto para a memória local, conforme o exemplo a seguir:

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
$provider = new EnvironmentVariableCredentialsProvider();
// The following example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name.
$bucket= "yourBucketName";
// Specify the object name. The object name is the full path of the object that does not include the bucket name, such as exampledir/exampleobject.txt.
$object = "yourObjectName";

try{
    $options = array(
        OssClient::OSS_HEADERS => array(          
          // Download the object if it was modified after Fri, 9 Apr 2021 14:47:53 GMT.
          OssClient::OSS_IF_MODIFIED_SINCE => "Fri, 9 Apr 2021 14:47:53 GMT",
          // Download the object if it was modified at or before Wed, 13 Oct 2021 14:47:53 GMT.
          OssClient::OSS_IF_UNMODIFIED_SINCE => "Fri, 13 Oct 2021 14:47:53 GMT",
          // Download the object if its ETag does not match the specified ETag.
          OssClient::OSS_IF_NONE_MATCH => '"5B3C1A2E0563E1B002CC607C****"',
          // Download the object if its ETag matches the specified ETag.
          OssClient::OSS_IF_MATCH => '"fba9dede5f27731c9771645a3986****"',
        )

    );

    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
    // Download the object to local memory.
    $content = $ossClient->getObject($bucket, $object, $options);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print ($content);
print(__FUNCTION__ . ": OK" . "\n");

Baixe um objeto para um arquivo local de forma condicional

Especifique as condições para baixe um objeto para um arquivo local, utilizando o código abaixo:

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
$provider = new EnvironmentVariableCredentialsProvider();
// The following example uses the endpoint of the China (Hangzhou) region. Replace the value with the actual endpoint.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Specify the bucket name.
$bucket= "yourBucketName";
// Specify the object name. The object name is the full path of the object that does not include the bucket name, such as exampledir/exampleobject.txt.
$object = "yourObjectName";
// Specify the full path of the local file. For example, D:\\localpath\\examplefile.txt.
$localfile = "yourLocalFile";

try{
    $options = array(
        OssClient::OSS_HEADERS => array(          
           // Download the object if it was modified after Fri, 9 Apr 2021 14:47:53 GMT.
          OssClient::OSS_IF_MODIFIED_SINCE => "Fri, 9 Apr 2021 14:47:53 GMT",
          // Download the object if it was modified at or before Wed, 13 Oct 2021 14:47:53 GMT.
          OssClient::OSS_IF_UNMODIFIED_SINCE => "Fri, 13 Oct 2021 14:47:53 GMT",
          // Download the object if its ETag does not match the specified ETag.
          OssClient::OSS_IF_NONE_MATCH => '"5B3C1A2E0563E1B002CC607C****"',
          // Download the object if its ETag matches the specified ETag.
          OssClient::OSS_IF_MATCH => '"fba9dede5f27731c9771645a3986****"',          
          OssClient::OSS_FILE_DOWNLOAD => $localfile
        )

    );

    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
    $ossClient->getObject($bucket, $object, $options);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}