PHP to determine if a request comes from a specific referrer


PHP Code to Determine if a Request Comes from a Specific Referrer

<?php
// Check if the request has a HTTP_REFERER header
if (isset($_SERVER['HTTP_REFERER'])) {
    // Get the referrer URL
    $referrer = $_SERVER['HTTP_REFERER'];
    
    // Check if the referrer matches the expected URL
    if ($referrer == 'https://www.example.com/referrer-page') {
        // The request came from the expected referrer
        echo 'The request came from the expected referrer.';
    } else {
        // The request did not come from the expected referrer
        echo 'The request did not come from the expected referrer.';
    }
} else {
    // The request does not have a HTTP_REFERER header
    echo 'The request does not have a HTTP_REFERER header.';
}
?>

How it Works

This code uses the HTTP_REFERER header to determine the URL of the page that referred the user to the current page. If the HTTP_REFERER header is not present, the code assumes that the user came directly to the current page.

The code then compares the value of the referrer with the expected referrer URL. If the values match, the code concludes that the request came from the expected referrer. Otherwise, the code concludes that the request did not come from the expected referrer.

How to Implement

To implement this code, you can add it to the beginning of your PHP script. For example, if you have a script that processes form submissions, you can add this code to the top of the script to check if the request came from the expected form page:

<?php
if (isset($_SERVER['HTTP_REFERER'])) {
    $referrer = $_SERVER['HTTP_REFERER'];
    
    if ($referrer != 'https://www.example.com/form-page') {
        // The request did not come from the expected form page
        header('Location: https://www.example.com/error-page');
        exit;
    }
}
?>

This code will redirect the user to an error page if the request did not come from the expected form page.