How to get the previous page URL in PHP?

Getting the previous page URL in PHP can be useful for things like breadcrumbs, redirects, analytics, etc. In any case, knowing the previous page URL is essential for understanding how users are interacting with your site.

Here are a few methods to get the referer or previous page URL in PHP.

Using $_SERVER[‘HTTP_REFERER’]

The $_SERVER superglobal variable contains information about the web server environment.

One of those values is ‘HTTP_REFERER’ which contains the address of the previous web page that linked to the currently requested page.

Get Exact Previous Page URL

$prevURL = $_SERVER['HTTP_REFERER'];

This will give you the exact URL of the previous page.

Check if Referer Exists

You’ll want to check if it exists first, since it won’t be set on first page load:

<?php
	
	if( isset( $_SERVER['HTTP_REFERER'] ) ){
		echo $_SERVER['HTTP_REFERER'];
	}else{
		echo "direct access";
	}
?>

Caveats of Referer

Some caveats of relying on the referer:

  • Not set on first page load
  • Can be disabled/spoofed by privacy software
  • Won’t work across different domains

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

Notice: Undefined index: HTTP_REFERER

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'] ) )

So while useful, be aware it may not always be available.

Get Previous Page URL from $_SERVER[‘REQUEST_URI’]

The REQUEST_URI contains the full URL of the currently requested page. We can parse this to try to determine the previous page on the same site:

$uri = $_SERVER['REQUEST_URI'];
$path = parse_url($uri, PHP_URL_PATH);
$prevPage = basename($path);

This makes some assumptions but can work on simple sites. More robust parsing would be needed for variable/complex URLs.

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:

<?php
	// create curl resource
	$ch = curl_init();
	
	curl_setopt($ch, CURLOPT_URL, "https://codehasbug.com");
	
	//fake referer
	curl_setopt($ch, CURLOPT_REFERER, "https://google.com");
	
	//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
	curl_close($ch);     
	
	return $output;
?>

This creates a stream context and adds a custom Referer header to the request.

You need to make sure any external requests are made using the stream wrapper so the custom headers are attached.

Spoofing the referrer domain can trick analytics scripts, influence ad clicks, bypass hotlink protection, and confuse tracking tools. But modifying request headers might be against terms of service.

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:

<?php
    session_start(); 
    $_SESSION['prev_loc'] = 'home';
?>

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

<?php
    echo $_SESSION['prev_loc'];
?>

Use JavaScript to Pass Previous Page

Another method is to use JavaScript on each page to pass the previous page URL to the next page load. This approach has wider browser support but depends on JavaScript being enabled.

First set a cookie or local storage value with the current page, then on next load read that stored previous value.

JavaScript Example

On each page:

localStorage.setItem('prevPage', window.location); 
const prevURL = localStorage.getItem('prevPage');

Then in PHP just look for the prevURL value, either passed through GET/POST or via Javascript API.

So in summary – a few options to get the previous URL for your PHP application!

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