在 PHP 中確定 referer
Sarwan Soomro
2022年5月13日
$_SERVER['HTTP_REFERER']
為我們提供了引用 URL
來確定伺服器上的使用者請求。但是,這不是最佳實踐,因為引用者可能會通過 HTTP
受到損害。
在 PHP 中使用 $_SESSION[]
確定引用者
由於 HTTP_REFERER
可以被欺騙/偽造,PHP 允許我們使用會話/cookie 來確定傳入的使用者請求是否來自你的域(伺服器)。
我們將為本教程建立兩個演示頁面。
userrequest.php
:在URL
中儲存使用者session id
,將其設定為true
並應用mt_rand()
以幫助增加安全性。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>
輸出:
請務必注意,雖然確定 referer
的傳統方法在大多數情況下並不可靠,但仍被廣泛使用。為了更安全,我們建議使用 session
或 (AJAX
) 而不是 HTTP
。
Author: Sarwan Soomro
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