edit-icon download-icon

Anti-leech

Last Updated: Aug 07, 2018

The OSS is a Pay-As-You-Go service. To prevent users’ data on the OSS from being leeched, the OSS supports anti-leech based on the field referer in the HTTP header.

For more information, see Anti-leech.

Note: Complete code for the following scenarios can be found at GitHub.

Configure a Referer whitelist

You can set a referer whitelist through OssClient::putBucketReferer:

  1. <?php
  2. /**
  3. * Configure anti-leech for a bucket
  4. *
  5. * @param OssClient $ossClient OSSClient instance
  6. * @param string $bucket Bucket name
  7. * @return null
  8. */
  9. function putBucketReferer($ossClient, $bucket)
  10. {
  11. $refererConfig = new RefererConfig();
  12. $refererConfig->setAllowEmptyReferer(true);
  13. $refererConfig->addReferer("www.aliiyun.com");
  14. $refererConfig->addReferer("www.aliiyuncs.com");
  15. try{
  16. $ossClient->putBucketReferer($bucket, $refererConfig);
  17. } catch(OssException $e) {
  18. printf(__FUNCTION__ . ": FAILED\n");
  19. printf($e->getMessage() . "\n");
  20. return;
  21. }
  22. print(__FUNCTION__ . ": OK" . "\n");
  23. }

Note: The referer parameters support the wildcard * and ?. For more information about rule configuration, see OSS Anti-Leech.

Retrieve a Referer whitelist

You can get a referer whitelist through OssClient::getBucketReferer:

  1. <?php
  2. /**
  3. * Get the anti-leech configuration of a bucket
  4. *
  5. * @param OssClient $ossClient OSSClient instance
  6. * @param string $bucket Bucket name
  7. * @return null
  8. */
  9. function getBucketReferer($ossClient, $bucket)
  10. {
  11. $refererConfig = null;
  12. try{
  13. $refererConfig = $ossClient->getBucketReferer($bucket);
  14. } catch(OssException $e) {
  15. printf(__FUNCTION__ . ": FAILED\n");
  16. printf($e->getMessage() . "\n");
  17. return;
  18. }
  19. print(__FUNCTION__ . ": OK" . "\n");
  20. print($refererConfig->serializeToXml() . "\n");
  21. }

Clear a Referer whitelist

The Referer whitelist cannot be cleared directly. You can only reset it to overwrite the previous rules.

  1. <?php
  2. /**
  3. * Delete the anti-leech configuration of a bucket
  4. * The referer whitelist cannot be cleared directly. You can only reset it to overwrite the previous rules.
  5. *
  6. * @param OssClient $ossClient OSSClient instance
  7. * @param string $bucket Bucket name
  8. * @return null
  9. */
  10. function deleteBucketReferer($ossClient, $bucket)
  11. {
  12. $refererConfig = new RefererConfig();
  13. try{
  14. $ossClient->putBucketReferer($bucket, $refererConfig);
  15. } catch(OssException $e) {
  16. printf(__FUNCTION__ . ": FAILED\n");
  17. printf($e->getMessage() . "\n");
  18. return;
  19. }
  20. print(__FUNCTION__ . ": OK" . "\n");
  21. }
Thank you! We've received your feedback.