Tous les produits
Search
Centre de documentation

Object Storage Service:Protection contre le hotlinking à l'aide du SDK OSS pour PHP 2.0

Dernière mise à jour :Sep 22, 2026

Utilisez le SDK OSS pour PHP 2.0 afin de configurer des politiques de contrôle d'accès s'appuyant sur l'en-tête de requête Referer. Cette approche vous permet de définir une liste d'autorisation Referer, une liste de blocage Referer et de choisir si les requêtes avec un en-tête Referer vide sont autorisées. En appliquant ces règles, vous empêchez efficacement le hotlinking non autorisé de vos ressources et réduisez les coûts de transfert de données inutiles.

Remarques relatives à l'utilisation

  • Avant de configurer la protection contre le hotlinking, assurez-vous de bien comprendre le fonctionnement de cette fonctionnalité. Pour plus d'informations, consultez la rubrique Protection contre le hotlinking.

  • Les exemples de code présentés dans cette rubrique utilisent la région Chine (Hangzhou) (cn-hangzhou) à titre d'exemple. Par défaut, le point de terminaison public est utilisé. Si vous souhaitez accéder à OSS depuis un autre service Alibaba Cloud situé dans la même région, utilisez le point de terminaison interne. Pour obtenir la liste complète des régions et des points de terminaison pris en charge, consultez la rubrique Régions et points de terminaison.

  • La définition ou la suppression des configurations de protection contre le hotlinking nécessite l'autorisation oss:PutBucketReferer, tandis que la récupération de ces configurations nécessite l'autorisation oss:GetBucketReferer. Pour plus d'informations, consultez la rubrique Accorder des autorisations personnalisées à un utilisateur RAM.

Exemples de code

Définir la protection contre le hotlinking

Ce code montre comment configurer la protection contre le hotlinking :

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

Obtenir les paramètres de protection contre le hotlinking

Ce code montre comment récupérer la configuration de protection contre le hotlinking :

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

Références

  • Pour plus d'informations sur l'opération API utilisée pour définir la protection contre le hotlinking, consultez la rubrique PutBucketReferer.

  • Pour plus d'informations sur l'opération API utilisée pour obtenir les configurations de protection contre le hotlinking, consultez la rubrique GetBucketReferer.