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.
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.
Leave a Reply
Related posts