How to Get the Referrer URL in PHP

09/06/2021

Contents

In this article, you will learn how to get the referrer URL in PHP.

The $_SERVER[‘HTTP_REFERER’] Variable

To get the referrer URL in PHP, you can use the $_SERVER[‘HTTP_REFERER’] variable.

Here is an example:

<?php
  $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
  echo "The referrer URL is: " . $referrer;
?>

It is important to note that the HTTP_REFERER header may not be present in all cases, so it is recommended to check if it is set before using it.

The $_SERVER variable in PHP is an array that contains information about the headers, paths, and script locations. The HTTP_REFERER element of the $_SERVER array contains the URL of the page that referred the user to the current page.

For example, if a user clicks a link on page A that leads to page B, the referrer URL of page B would be the URL of page A.

It’s worth mentioning that the value of the HTTP_REFERER header can be easily altered by the client and is therefore not 100% reliable. In some cases, the referrer may not be sent at all, for example, if the user types the URL directly into the address bar or if they are coming from a secure connection (HTTPS) to an insecure connection (HTTP). In such cases, the HTTP_REFERER variable will not be set and attempting to access it may result in an undefined index notice.

In conclusion, the HTTP_REFERER header is a useful tool for determining where a user came from, but it should not be relied on for secure or critical information.