It looks like you're new here. If you want to get involved, click one of these buttons!
I would love built in CORS support for APIs. I saw one post on how to add CORS, but it uses the wildcard and opens the site up to any domain.
Even though I’ve never written php before, I was able to cobble together a temporary solution that can be pasted at the top of these API endpoints:
Code:
```
$origin = $_SERVER['HTTP_ORIGIN'];
function get_domain($host){
$myhost = strtolower(trim($host));
$count = substr_count($myhost, '.');
if($count === 2){
if(strlen(explode('.', $myhost)[1]) > 3) $myhost = explode('.', $myhost, 2)[1];
} else if($count > 2){
$myhost = get_domain(explode('.', $myhost, 2)[1]);
}
return $myhost;
}
$origin_domain = get_domain($origin);
$allowed_domains = [
'example.com',
'example.org',
'example.net',
];
if (in_array($origin_domain, $allowed_domains)) {
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Origin: ' . $origin);
}
```
Please note that $allowed_domains includes all subdomains.
Also, a note for others using fetch/axios. The content-type must be application/x-www-form-urlencoded;charset=UTF-8
, and the body can be built using the querystring package or URLSearchParams.
References