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.
userrequest.php
: Stored usersession id
inURL
, set ittrue
and appliedmt_rand()
to aid additional security.determineuser.php
: Determined referer (domain/server) location usingsession
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:
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 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