How can the $_SERVER variable be utilized to check the referer in PHP and ensure accurate verification?

When checking the referer using the $_SERVER variable in PHP, it's important to ensure accurate verification to prevent spoofing or manipulation. One way to do this is by comparing the referer value with the expected value or domain. This can help verify that the request is coming from a trusted source.

if(isset($_SERVER['HTTP_REFERER']) && parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) == 'example.com'){
    // Valid referer
    // Proceed with the code
} else {
    // Invalid referer
    // Handle the error or redirect
}