在 PHP 中确定 referer

Sarwan Soomro 2022年5月13日
在 PHP 中确定 referer

$_SERVER['HTTP_REFERER'] 为我们提供了引用 URL 来确定服务器上的用户请求。但是,这不是最佳实践,因为引用者可能会通过 HTTP 受到损害。

在 PHP 中使用 $_SESSION[] 确定引用者

由于 HTTP_REFERER 可以被欺骗/伪造,PHP 允许我们使用会话/cookie 来确定传入的用户请求是否来自你的域(服务器)。

我们将为本教程创建两个演示页面。

  1. userrequest.php:在 URL 中存储用户 session id,将其设置为 true 并应用 mt_rand() 以帮助增加安全性。
  2. determineuser.php:使用 session$_SERVER['HTTP_REFERER'] 确定引荐来源(域/服务器)位置。

userrequest.php 代码:

<!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 代码:

<?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>

输出:

在 PHP 中确定 REFERER

请务必注意,虽然确定 referer 的传统方法在大多数情况下并不可靠,但仍被广泛使用。为了更安全,我们建议使用 session 或 (AJAX) 而不是 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