How to Determine Referer in PHP

Sarwan Soomro Feb 02, 2024
How to Determine Referer in PHP

The $_SERVER['HTTP_REFERER'] gives us referer URL to determine user requests on the server. But, it is not a best practice since the referer can be compromised over HTTP.

Determine Referer Using $_SESSION[] in PHP

Since the HTTP_REFERER can be spoofed/faked, PHP allows us to use sessions/cookies to determine whether an incoming user request is from your domain (server) or not.

We will create two demo pages for this tutorial.

  1. userrequest.php: Stored user session id in URL, set it true and applied mt_rand() to aid additional security.
  2. determineuser.php: Determined referer (domain/server) location using session and $_SERVER['HTTP_REFERER'].

userrequest.php code:

<!DOCTYPE html>
<body>
  <form action ="determineuser.php" method ="post" align="center">
  <input type ="submit" name="click" value="Determine user request through session"/>

<?php
session_start(); //first we start session
$setsession = uniqid(mt_rand(), TRUE); //Set it true, assign mt_rand to ensure secuity
$_SESSION['set'] = $setsession;
//we can use url to export session over servers
$redirect = "determineuser.php?set={$setsession}"; // this url can be on any server
?>

<br>
<h1 align="center">

<?php
echo "Your current session is:".$_SESSION['set']; //check session on page 1
echo"<br>";
?>
</form>
</body>
</html>

determineuser.php code:

<?php
session_start(); //check if the session and form input is 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'];
?>

<h1 align="center">
<p> This is the secure way to determine referer using session:</p>

<?php
echo $_SESSION['set'];//check session on page 2 (compare to determine from the last page)
?>

</h1>

<?php
  } else {
//if the domain referer is not determined, header function will redirect the user page to the last page
  header('Location:userrequest.php');
  exit; //exit to release unnessary server load
}
?>
</form>
</body>
</html>

Output:

Determine REFERER in PHP

It’s important to note that while the traditional method of determining a referer is unreliable in most cases, it’s still widely used. To be more secure, we propose using session or (AJAX) instead of HTTP.

Sarwan Soomro avatar Sarwan Soomro avatar

Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.

LinkedIn