What are the best practices for implementing domain-based access control in PHP to prevent unauthorized access?

To implement domain-based access control in PHP to prevent unauthorized access, you can check the domain of the incoming request against a whitelist of allowed domains. This ensures that only requests originating from specified domains are granted access to the application.

$allowed_domains = ['example.com', 'subdomain.example.com'];

if (isset($_SERVER['HTTP_REFERER'])) {
    $referer_domain = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
    
    if (!in_array($referer_domain, $allowed_domains)) {
        die('Unauthorized access');
    }
} else {
    die('Unauthorized access');
}

// Proceed with the rest of the application logic