CORS

Last Updated: Nov 02, 2017

Cross-origin Resource Sharing (CORS) allows web applications to access resources in other domains. OSS provides an interface for developers to conveniently control cross-origin access permissions.

For more information about CORS, see CORS Access.

Note: For complete code, see GitHub.

Set CORS rules

The putBucketCors method is used to configure a CORS rule for a specified bucket. If the original CORS rule already exists, it gets overwritten by the new one. Parameters for specific rules are generally set through the CORSRule class.

You can set the bucket CORS rules using OssClient::putBucketCors:

  1. <?php
  2. /**
  3. * Configure CORS for a bucket
  4. *
  5. * @param OssClient $ossClient OSSClient instance
  6. * @param string $bucket Bucket name
  7. * @return null
  8. */
  9. function putBucketCors($ossClient, $bucket)
  10. {
  11. $corsConfig = new CorsConfig();
  12. $rule = new CorsRule();
  13. $rule->addAllowedHeader("x-oss-header");
  14. $rule->addAllowedOrigin("http://www.b.com");
  15. $rule->addAllowedMethod("POST");
  16. $rule->setMaxAgeSeconds(10);
  17. $corsConfig->addRule($rule);
  18. try{
  19. $ossClient->putBucketCors($bucket, $corsConfig);
  20. } catch(OssException $e) {
  21. printf(__FUNCTION__ . ": FAILED\n");
  22. printf($e->getMessage() . "\n");
  23. return;
  24. }
  25. print(__FUNCTION__ . ": OK" . "\n");
  26. }

Note:

  • Each bucket allows up to 10 CORS rules.

  • The AllowedOrigins and AllowedMethods each supports up to one * wildcard. * indicates that all origin sources or operations are allowed.

  • AllowedHeaders and ExposeHeaders do not support wildcards.

Get CORS rules

You can get the bucket CORS rules using OssClient::getBucketCors:

  1. <?php
  2. /**
  3. * Get and print the CORS rules of a bucket
  4. *
  5. * @param OssClient $ossClient OSSClient instance
  6. * @param string $bucket Bucket name
  7. * @return null
  8. */
  9. function getBucketCors($ossClient, $bucket)
  10. {
  11. $corsConfig = null;
  12. try{
  13. $corsConfig = $ossClient->getBucketCors($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($corsConfig->serializeToXml() . "\n");
  21. }

Delete a CORS rule

You can disable and clear all the CORS rules of a bucket using OssClient::deleteBucketCors:

  1. <?php
  2. /**
  3. * Delete all CORS rules of a bucket
  4. *
  5. * @param OssClient $ossClient OSSClient instance
  6. * @param string $bucket Bucket name
  7. * @return null
  8. */
  9. function deleteBucketCors($ossClient, $bucket)
  10. {
  11. try{
  12. $ossClient->deleteBucketCors($bucket);
  13. } catch(OssException $e) {
  14. printf(__FUNCTION__ . ": FAILED\n");
  15. printf($e->getMessage() . "\n");
  16. return;
  17. }
  18. print(__FUNCTION__ . ": OK" . "\n");
  19. }
Thank you! We've received your feedback.