What are some best practices for handling HTTP-Referer manipulation in PHP to avoid unintended consequences?

HTTP-Referer manipulation can lead to security vulnerabilities by allowing attackers to spoof the referring URL. To mitigate this risk, it's essential to validate and sanitize the HTTP-Referer header before using it in any sensitive operations. One way to do this is by checking if the Referer header matches the expected domain or URL pattern.

// Validate and sanitize the HTTP-Referer header
$expectedReferer = "https://example.com";
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

if (strpos($referer, $expectedReferer) === false) {
    // Handle unauthorized access or redirect to a safe page
    header("Location: https://example.com/error.php");
    exit();
}

// Proceed with the sensitive operation
// Your code here...