Todos os produtos
Search
Central de documentação

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

Última atualização: Sep 22, 2026

Use o OSS SDK for PHP 2.0 e configure políticas de controle de acesso baseadas no header de requisição Referer. Isso permite que você defina uma lista de permissões de Referer, uma lista de bloqueios de Referer e escolha se deseja permitir requisições com um header Referer vazio. Ao implementar essas regras, você evita de forma eficaz o hotlink não autorizado dos seus recursos e reduz custos desnecessários de transferência de dados.

Notas de uso

  • Antes de configurar a proteção contra hotlink, certifique-se de entender como esse recurso funciona. Para mais informações, consulte Hotlink protection.

  • O código de exemplo neste tópico usa a região China (Hangzhou) (cn-hangzhou) como exemplo. Por padrão, o SDK usa o endpoint público. Se você quiser acessar o OSS a partir de outro service do Alibaba Cloud na mesma região, use o endpoint interno. Para uma lista completa de regiões e endpoints suportados, consulte Regions and endpoints.

  • Definir ou limpar configurações de proteção contra hotlink requer a permissão oss:PutBucketReferer, enquanto obter configurações de proteção contra hotlink requer a permissão oss:GetBucketReferer. Para mais informações, consulte Grant custom permissions to a RAM user.

Código de exemplo

Defina a proteção contra hotlink

Este código mostra 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.
);

Obter configurações de proteção contra hotlink

Este código mostra como obter 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 mais informações sobre a operação de API usada para definir a proteção contra hotlink, consulte PutBucketReferer.

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