Current Location: Home> Latest Articles> PHP Methods to Get and Securely Validate Referer

PHP Methods to Get and Securely Validate Referer

M66 2025-10-05

Introduction to Referer in PHP

In web development, the Referer is part of the HTTP request header that indicates the source page of a request. By obtaining the Referer, you can implement features such as hotlink protection and tracking user origins. However, it is important to note that the HTTP_REFERER header can easily be forged, making it unreliable in security-sensitive contexts.

Using Session to Validate Request Source

Since the HTTP_REFERER value can be spoofed, a safer approach is to use Session or Cookie to validate whether a request originated from your own page. The following examples demonstrate how to implement this.

Example: userrequest.php

<!DOCTYPE html>
<html>
<body>
<form action="determineuser.php" method="post" align="center">
    <input type="submit" name="click" value="Determine user request through session"/>
</form>
<?php
session_start(); // Start the session
$setsession = uniqid(mt_rand(), TRUE); // Generate a unique identifier
$_SESSION['set'] = $setsession;
$redirect = "determineuser.php?set={$setsession}"; // Session token can be passed

echo "<h1 align='center'>";
echo "Your current session is:".$_SESSION['set']; // Display Session on the page
echo "</h1>";
?>
</body>
</html>

Example: determineuser.php

<?php
session_start(); // Check if Session and form submission are set
if ( (isset($_SESSION['set']) && $_SESSION['set'] === TRUE) || isset($_POST['click']) ) {
    echo "Determined Last visited page on the server using HTTP REFERER:<br>".$_SERVER['HTTP_REFERER'];
    echo "<h1 align='center'>";
    echo "<p>This is the secure way to determine referer using session:</p>";
    echo $_SESSION['set']; // Validate Session consistency
    echo "</h1>";
} else {
    // If referer cannot be determined, redirect to userrequest.php
    header('Location:userrequest.php');
    exit;
}
?>

Conclusion

While using $_SERVER['HTTP_REFERER'] directly is simple, it is not secure. In situations where security is critical, it is recommended to use Session or Ajax to validate the request source and prevent forged Referer values from being exploited.