What are the best practices for handling HTTP_REFERER in PHP scripts to ensure security and accuracy?

When handling the HTTP_REFERER header in PHP scripts, it is important to validate and sanitize the data to prevent security vulnerabilities such as CSRF attacks. One way to do this is by checking if the referer URL matches the expected domain before using it in your application. Additionally, you can use a whitelist approach to only allow specific domains to be accepted as valid referrers.

$valid_referer = 'https://www.example.com';

if(isset($_SERVER['HTTP_REFERER']) && parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) === parse_url($valid_referer, PHP_URL_HOST)) {
    // Proceed with processing the request
} else {
    // Handle unauthorized access or redirect to a safe location
}