How to get the previous page URL in PHP?

There are many times when you need to know the previous page URL after a redirect. Maybe you’re wondering where your traffic is coming from, or if a particular campaign is driving users to your site. In any case, knowing the previous page URL is essential for understanding how users are interacting with your site.

Fortunately, it’s easy to get this information using some simple code. Keep reading to learn how!


How to get the previous page URL using PHP?

$_SERVER['HTTP_REFERER'] always contains the referrer or referring page URL. When you want to get the previous page’s URL, use this code:

	if( isset( $_SERVER['HTTP_REFERER'] ) ){
		echo "direct access";

However, you should know that someone can change the $_SERVER['HTTP_REFERER'] header at any time. This will not tell you if they have been to a website before.

Sometimes you may notice a warning like

<strong>Notice: Undefined index: HTTP_REFERER</strong>

Some user agents don’t set HTTP_REFERER, and others let you change HTTP_REFERER. So it’s not a reliable piece of information. So, always check if it is set or not by using isset().

if( isset( $_SERVER['HTTP_REFERER'] ) )

How to spoof HTTP_REFERER?

It’s very easy to spoof as well as there are many ways to grab the header from the user. This is a very common problem that I have come across in almost every single web application which requires the referer check to be enabled.

Referer spoofing is a simple process and can often be done by any individual who has little knowledge of the HTTP protocol. Let’s look at how it works:

	// create curl resource
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "");
	//fake referer
	curl_setopt($ch, CURLOPT_REFERER, "");
	//return the transfer as a string
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	// $output contains the output string
	$output = curl_exec($ch);

	// close curl resource to free up system resources
	return $output;

How to get the previous page URL after redirect in PHP?

The best way to get the previous URL is with the PHP session. The value for $_SESSION[‘previous_location’] will be set as the previous page URL after a redirect.

Now set the session on your homepage like this:

    $_SESSION['prev_loc'] = 'home';

You can access this session variable from any page like this:

    echo $_SESSION['prev_loc'];

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment