Are there more secure alternatives to using HTTP_REFERER for domain validation in PHP?

Using HTTP_REFERER for domain validation in PHP is not secure as it can be easily spoofed. A more secure alternative is to use a combination of cryptographic techniques such as HMAC or digital signatures to validate the origin of the request.

// Example using HMAC for domain validation
$secretKey = 'your_secret_key';
$expectedDomain = 'example.com';

if(isset($_SERVER['HTTP_REFERER'])) {
    $referer = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
    $hmac = hash_hmac('sha256', $referer, $secretKey);

    if(hash_equals($hmac, $_GET['hmac']) && $referer === $expectedDomain) {
        // Valid request
    } else {
        // Invalid request
    }
} else {
    // HTTP_REFERER not set
}