What are some best practices for ensuring secure page referrals in PHP applications?

Secure page referrals in PHP applications can be ensured by checking the referrer header in the HTTP request to verify that the request is coming from an authorized source. This helps prevent unauthorized access to sensitive pages and protects against CSRF attacks. One best practice is to compare the referrer header with a list of allowed domains or URLs to ensure that the request is legitimate.

// Check if the referrer header is set
if(isset($_SERVER['HTTP_REFERER'])) {
    $referrer = $_SERVER['HTTP_REFERER'];
    
    // List of allowed domains or URLs
    $allowed_domains = array('https://example.com', 'https://subdomain.example.com');
    
    // Check if the referrer is in the list of allowed domains
    if(in_array($referrer, $allowed_domains)) {
        // Proceed with the request
    } else {
        // Redirect or display an error message
        header('Location: error.php');
        exit;
    }
} else {
    // Redirect or display an error message
    header('Location: error.php');
    exit;
}