Restricting access to a page based on the referrer.

As you probably already know, PHP has an array called $_SERVER, which contains information such as:

  • The server name.
  • The request method (whether the request is POST, GET or PUT, etc).
  • The IP address of the user.
  • The visitor’s user agent.

It has also has an index called HTTP_REFERER, which should give you the address of the page that referred the user. Code example:

In the perfect world, the above piece of code would give you URL of the page that referred the user to your current page.

Unfortunately, we do not live in a perfect world.

You see, the problem with $_SERVER[‘HTTP_REFERER’] is that is can be spoofed by the person or the process that is accessing the page. In fact, many proxy services will actually remove this information from the request.

All in all, this means that the $_SERVER[‘HTTP_REFERER’] variable can not be trusted.

So, what can I do?

A better approach is to use sessions.

Let us say, for example, that we want to make sure that a user visiting page-two.php has come from page-one.php. On page-one.php, we can set a session variable like so:

In the code above, we’ve created a session variable called page_one and we’ve assigned the current timestamp to it.

Then, on page-two.php, we can check to see if this session variable has been set or not. If it has been set, we can make the assumption that the user has visited page-one.php. If it is not set, then we can assume that the user has not visited page-one.php.

If the session variable in question does not exist, we restrict access to the page by forcibly redirecting the user back to page-one.php