Home >Backend Development >PHP Tutorial >Determine referer in PHP
php editor Strawberry will introduce to you today how to determine referer in PHP. The referer is part of the HTTP request header and is used to identify the source page of the request. During the development process, it is sometimes necessary to obtain referer information to implement specific functions, such as anti-leeching, statistical analysis, etc. Referer information can be easily obtained through PHP to implement related functions. Next, we will introduce in detail how to determine the referer in PHP, so that everyone can easily master this technique.
N[]<strong class="keylink"> in </strong>PHP
to determine the referrer
Since HTTP_REFERER
can be spoofed/forged, php allows us to use sessions/cookies to determine if incoming user requests are coming from your domain (server).
We will create two demo pages for this article.
userrequest.php
Code:
<code> <code class="language-php+HTML hljs" data-lang="php+HTML"><!DOCTYPE <strong class="keylink">html</strong>> <body> <f<strong class="keylink">ORM</strong> 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> </code></code>
determineuser.php
Code:
<code> <code class="language-php+HTML hljs" data-lang="php+HTML"><?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 dom<strong class="keylink">ai</strong>n 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> </code></code>
Output:
It is important to note that although the traditional method of determining referer
is unreliable in most cases, it is still widely used. For more security, we recommend using session
or (<strong class="keylink">ajax</strong>
) instead of HTTP
.
The above is the detailed content of Determine referer in PHP. For more information, please follow other related articles on the PHP Chinese website!