Todos os produtos
Search
Central de documentação

Object Storage Service:Proteção contra hotlink com o OSS SDK for PHP 2.0

Última atualização: Jul 03, 2026

Use o OSS SDK for PHP 2.0 para configurar políticas de controle de acesso baseadas no cabeçalho de requisição Referer. Esse recurso permite definir uma lista de permissões de Referer, uma lista de bloqueios de Referer e escolher se requisições com cabeçalho Referer vazio serão aceitas. A aplicação dessas regras evita o hotlinking não autorizado dos seus recursos e reduz custos desnecessários com transferência de dados.

Observações de uso

  • Antes de configurar a proteção contra hotlink, certifique-se de compreender o funcionamento desse recurso. Para mais informações, consulte Proteção contra hotlink.

  • Os exemplos de código deste tópico usam a região China (Hangzhou) (cn-hangzhou) como referência. Por padrão, o sistema usa o endpoint público. Caso precise acessar o OSS a partir de outro serviço da Alibaba Cloud na mesma região, use o endpoint interno. Para obter a lista completa de regiões e endpoints compatíveis, consulte Regiões e endpoints.

  • Definir ou limpar configurações de proteção contra hotlink exige a permissão oss:PutBucketReferer, enquanto a obtenção dessas configurações requer a permissão oss:GetBucketReferer. Para mais detalhes, consulte Conceder permissões personalizadas a um usuário RAM.

Exemplos de código

Set hotlink protection

O código abaixo demonstra como configurar a proteção contra hotlink:

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define the command-line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // The region is required. This is the region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // The endpoint is optional. This is the domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name is required.
];

// Generate a list of long options to parse command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each parameter to indicate that a value is required.
}, array_keys($optsdesc));

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

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

// Obtain argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Use environment variables to load credential information, including AccessKeyId and AccessKeySecret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a request object to set the hotlink protection configuration for the bucket. Configure allowEmptyReferer to false and set the Referer list.
$request = new Oss\Models\PutBucketRefererRequest(bucket: $bucket,
    refererConfiguration: new Oss\Models\RefererConfiguration(
        allowEmptyReferer: false,
        refererList: new Oss\Models\RefererList([""]),
    )
);

// Call the putBucketReferer method to set the hotlink protection configuration for the bucket.
$result = $client->putBucketReferer($request);

// Print the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId // The unique identifier of the request.
);

Obtain hotlink protection settings

Este trecho ilustra como recuperar a configuração de proteção contra hotlink:

<?php

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

use AlibabaCloud\Oss\V2 as Oss;

// Define the command-line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // The region is required. This is the region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // The endpoint is optional. This is the domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name is required.
];

// Generate a list of long options to parse command-line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each parameter to indicate that a value is required.
}, array_keys($optsdesc));

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

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

// Obtain the command-line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.

// Use environment variables to load credential information, including AccessKeyId and AccessKeySecret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a request object to obtain the hotlink protection configuration of the bucket.
$request = new Oss\Models\GetBucketRefererRequest(bucket: $bucket);

// Call the getBucketReferer method to obtain the hotlink protection configuration of the bucket.
$result = $client->getBucketReferer($request);

// Print the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId . PHP_EOL . // The unique identifier of the request.
    'referer config:' . var_export($result->refererConfiguration, true) // The hotlink protection configuration.
);

Referências

  • Para obter mais informações sobre a operação de API usada para definir a proteção contra hotlink, consulte PutBucketReferer.

  • Para obter mais informações sobre a operação de API usada para obter configurações de proteção contra hotlink, consulte GetBucketReferer.