VPS business hosting starting at $29.95/24/7 premium technical support

How to limit ajax apis for your origins (Access-Control-Allow-Origin headers)

$allowed_domains = ["https://www.YOURDOMAIN.com","https://YOURDOMAIN.com","https://staging.YOURDOMAIN.com","https://www.YOURDOMAIN.com/","https://YOURDOMAIN.com/","https://staging.YOURDOMAIN.com/"];
// echo $_SERVER['HTTP_ORIGIN'];
if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {
    header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}
else{
    if(in_array($_SERVER['HTTP_REFERER'], $allowed_domains)){
        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_REFERER']);
    }
}

Author: Harshvardhan Malpani

PHP Developer based in New Delhi, India. Working as a freelance web developer providing server deployment, website development and maintenance services.

Leave a Reply

Your email address will not be published.