Get Referrer URL in PHP: Easy Steps

When developing a website or web application, it can be useful to know the URL of the website or page that a user was on before they arrived at your site. This information, known as the "referrer URL", can be easily obtained using PHP.

Índice
  1. Step 1: Check for Referrer URL
  2. Step 2: Sanitize Referrer URL
  3. Conclusion

Step 1: Check for Referrer URL

To get the referrer URL in PHP, you first need to check if it exists. This can be done using the isset() function. Here's an example:

<?php
if(isset($_SERVER['HTTP_REFERER'])) {
  $referrer = $_SERVER['HTTP_REFERER'];
  echo "Referrer URL: " . $referrer;
} else {
  echo "No referrer URL.";
}
?>

In this example, we're using the $_SERVER superglobal array to access the referrer URL. If it exists, we assign it to the $referrer variable and then display it using echo. If it doesn't exist, we display a message saying so.

Step 2: Sanitize Referrer URL

After obtaining the referrer URL, it's important to sanitize it to prevent any potential security issues. This can be done using the filter_var() function. Here's an example:

<?php
if(isset($_SERVER['HTTP_REFERER'])) {
  $referrer = $_SERVER['HTTP_REFERER'];
  $referrer = filter_var($referrer, FILTER_SANITIZE_URL);
  echo "Referrer URL: " . $referrer;
} else {
  echo "No referrer URL.";
}
?>

In this example, we're using the filter_var() function to sanitize the referrer URL. We're using the FILTER_SANITIZE_URL filter to remove any potentially malicious characters from the URL.

Conclusion

Getting the referrer URL in PHP is a simple process that can provide valuable information about your website's traffic. By checking for the referrer URL and sanitizing it, you can ensure that your website is secure and functioning properly.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information