Clue Mediator

Enable CORS for multiple domains in PHP

๐Ÿ“…July 19, 2021
๐Ÿ—PHP

Today, weโ€™ll explain to you how to permit CORS requests for multiple origins in PHP.

To get the response from a simple cross-origin ajax-post-request-with-jquery-and-php" title="Ajax POST request with jQuery and PHP">POST request, we need to include the header `Access-Control-Allow-Origin`. The specification of `Access-Control-Allow-Origin` allows for multiple origins, or the value `null`, or the wildcard `*`.

Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: https:mydomain.com
Access-Control-Allow-Origin: null

Checkout more articles on PHP

  • url-using-php" title="How to get Title and Meta tags from URL using PHP">How to get Title and Meta tags from URL using PHP
  • QR code using PHP">Generate QR code using PHP
  • bootstrap-modal-with-ajax-php-and-mysql" title="Load dynamic content in Bootstrap Modal with AJAX, PHP and MySQL">Load dynamic content in Bootstrap Modal with AJAX, PHP and MySQL
  • recaptcha-v3-in-php" title="Google reCAPTCHA v3 in PHP">Google reCAPTCHA v3 in PHP
  • Calculate the age from date of birth in PHP

Check the following code to enable CORS for multiple domains.

$allowedOrigins = [
   'https://example.com',
   'https://staging.example.com' ,
   'https://production.example.com' ,
];

if(in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins))
{
	$http_origin = $_SERVER['HTTP_ORIGIN'];
} else {
	$http_origin = "https://example.com";
}
header("Access-Control-Allow-Origin: $http_origin");

In the above code, we have taken an array of multiple domains which we want to allow in `Access-Control-Allow-Origin`.

Use the `$_SERVER['HTTP_ORIGIN']` variable to verify which domain the request comes from and then conditionally set the `Access-Control-Allow-Origin`.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐Ÿ™‚