What best practices should be followed when working with the HTTP_REFERER variable in PHP?

When working with the HTTP_REFERER variable in PHP, it is important to validate and sanitize the data to prevent security vulnerabilities such as cross-site scripting attacks. It is recommended to check if the variable is set and if it matches a trusted domain before using it in any way.

// Check if the HTTP_REFERER variable is set and matches a trusted domain
if(isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'https://example.com') !== false){
    // Use the HTTP_REFERER variable safely
    $referer = $_SERVER['HTTP_REFERER'];
    // Further processing here
} else {
    // Handle invalid or untrusted HTTP_REFERER values
    echo "Invalid or untrusted HTTP_REFERER value.";
}