Enable CORS for multiple domains in 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 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 *
.
1 2 3 | Access-Control-Allow-Origin: * Access-Control-Allow-Origin: https:mydomain.com Access-Control-Allow-Origin: null |
Checkout more articles on PHP
Check the following code to enable CORS for multiple domains.
1 2 3 4 5 6 7 8 9 10 11 12 13 | $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..!! 🙂