Redirect to Previous Page In PHP - Most Common Mistake

ann perkins

Often when user submit a form you want PHP to process form data and then redirect user to previous page. Generally, to go back to previous page in PHP you can use the following code snippet:

header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;

This code snippet is most used by beginner users. However there's a big problem in it.

The Problem

The $_SERVER is a PHP global variable and its value is an array contains server server information. The $_SERVER['HTTP_REFERER'] contains URL that referred to the current page (which is the page that processing submitted form data). However the problem with that code snippet is that the value of $_SERVER['HTTP_REFERER'] can be modified by the client and therefore this value CANNOT really be trusted. Let's take a look at one simple example to understand why this value cannot be trusted.

In your browser (prefer Chrome or Firefox), go to Google in search box you type in this phrase and then hit Enter:

HTML beginner tutorials beginnertutorials.net

You'll see several result as similar to the following:

Redirect to previous page in PHP

Now if you click on the first result and press Ctrl + J if you on Windows or Ctrl + option J + J if you on Mac OSX to open the console tab. Then click to the Network tab and type in beginnertutorial.net to the filter box as shown in the image below:

Redirect to previous page in PHP

Click to the first result and take a look at the right panel, you'll see this result:

Redirect to previous page in PHP

What it means is that the value of $_SERVER['HTTP_REFERER'] is actually taken from the header from request data which can be modified easily by client for example if you use client such as CURL to send the request.

The Better Way

Most often when doing redirect to a previous page, you will expect the previous page also has the same domain with current page (unlike the previous example). Which means on the server side, you will have the total control over the requested data taken from previous page request. For example to save the previous URL into session. For example in first_page.php:

session_start();

// update current visiting URL to do redirect later on (if needed)
$_SESSION["current_url"] =  $_SERVER["REQUEST_URI"];
...

And then in second page if you want to do redirect:


session_start();

// retrieve previous URL from session
$previousUrl = $_SESSION["current_url"];

// update current visiting URL to do redirect later on (if needed)
$_SESSION["current_url"] =  $_SERVER["REQUEST_URI"];
...

This way you don't rely on data provided by client but instead the data you have on your own server.

Reply