Todos los productos
Search
Centro de documentos

Object Storage Service:Descarga condicional (SDK de PHP V1)

Última actualización: Sep 22, 2026

La descarga condicional le permite especificar una o más condiciones al descargar un objeto de Object Storage Service (OSS). El objeto se descarga en la memoria local o en un archivo local únicamente si se cumplen las condiciones indicadas. Si no se cumplen, se devuelve un error y la descarga no inicia.

Notas de uso

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para obtener más información sobre las regiones y los endpoints compatibles, consulte Regions and endpoints.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Create an OssClient.

  • Para ejecutar una descarga condicional, necesita el permiso oss:GetObject. Para obtener más información, consulte Attach a custom policy to a RAM user.

Condiciones

A continuación se muestran las condiciones que admite OSS. Puede usar If-Modified-Since e If-Unmodified-Since de forma simultánea. También es posible combinar If-Match e If-None-Match.

Parámetro

Descripción

Método

If-Modified-Since

Si el objeto se modificó después de la hora especificada, se descarga. De lo contrario, se devuelve un error 304 Not modified.

OssClient::OSS_IF_MODIFIED_SINCE

If-Unmodified-Since

Si el objeto se modificó en la hora indicada o antes, se descarga. En caso contrario, se devuelve un error 412 Precondition failed.

OssClient::OSS_IF_UNMODIFIED_SINCE

If-Match

Si el ETag del objeto de OSS coincide con el ETag especificado, se descarga el objeto. Si no coinciden, se devuelve un error 412 Precondition failed.

Nota

Obtenga el ETag de un objeto mediante el método $ossClient->getObjectMeta.

OssClient::OSS_IF_MATCH

If-None-Match

Si el ETag del objeto de OSS no coincide con el ETag especificado, se descarga el objeto. Cuando coinciden, se devuelve un error 304 Not modified.

OssClient::OSS_IF_NONE_MATCH

Descarga condicional de un objeto en la memoria local

El siguiente código muestra cómo especificar condiciones para descargar un objeto en la memoria local:

<?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");

Descarga condicional de un objeto en un archivo local

El siguiente código muestra cómo especificar condiciones para descargar un objeto en un archivo local:

<?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;
}