Creating a Login Page That Returns to The Last Visited Page in PHP

Today I gonna post a tutorial about how to create a login page which returns to the last visited (refering) page on success.

Usually we see on many websites that when we do a login process, the website redirects to its homepage or account page if the login is successful. Creating this is quite easy. But sometimes we also see some websites (such as YouTube) redirects its user to the last visited page after logging in.

The main idea is quite simple. When a user go to the login page, the page find out the URL where the user comes from (in PHP this can be achieved by checking $_SERVER[‘HTTP_REFERER’] variable). This information is passed alongside with user credentials (username and password) to the login process page. So when the login succeed, the page can redirect the user to the provided URL.

Okay now let’s go into the business.

1. Create some pages.

In this tutorial we are going to make two simple pages that users can browse between them. Let’s make the first page:

index.php

<php
// Check session state
session_start();
if($_SESSION[‘is_logged_in’] == true)
$logged_in = true;
else
$logged_in = false;
?><h1>This is The First Page</h1>

<a href=”page2.php”>Go to the second page</a>

<?php if($logged_in) : ?>
<p>You are logged in.</p>
<a href=”logout.php”>Click here to logout</a>
<?php else : ?>
<a href=”login.php”>Click here to login</a>
<?php endif; ?>

Note: To simplify the code, the above lines is not a valid HTML document. When making a real pages you should write all the HTML, HEAD, and BODY tags in the correct form

We have two links: login and logout. Either of this links will be displayed based on user’s login state. When a user is logged in, the $_SESSION[‘is_logged_in’] is set to true. The session variable will be described later in this tutorial.

Next we make another page similar to the first one. You can just copy the file and make changes to its title to differentiate the latter from the first one.

page2.php

<php
// Check session state
session_start();
if($_SESSION[‘is_logged_in’] == true)
$logged_in = true;
else
$logged_in = false;
?><h1>This is The Second Page</h1>

<a href=”index.php”>Go to the first page</a>

<?php if($logged_in) : ?>
<p>You are logged in.</p>
<a href=”logout.php”>Click here to logout</a>
<?php else : ?>
<a href=”login.php”>Click here to login</a>
<?php endif; ?>

2. The Login Page.

We see that if we click on the “Click here to login” link, it will go to login.php. Now we make a simple login form with just username and password fields. But before that, we first check and get the URL where user comes from and assign it to a variable $redirect_to. We can know the information from $_SERVER[‘HTTP_REFERER’].

login.php

<?php
// Get the refering page (if unset)
if(!isset($redirect_to))
$redirect_to = $_SERVER[‘HTTP_REFERER’];
?>

Okay, then goes the login form:

<h1>Login</h1>

<form action=”login_submit.php” method=”POST”>
<label>
Username:<br />
<input type=”text” name=”username” value=”<?=@$username?>” /><br />
</label>
<label>
Password:<br />
<input type=”password” name=”password” /><br />
</label>
<input type=”submit” value=”Login” />
<input type=”hidden” name=”redirect_to” value=”<?=$redirect_to?>” />
</form>

<p><?=@$error?></p>

Inside the form we put a hidden value named “redirect_to” to pass the URL we get before to login_submit.php which will process the form.

Note: For you who are new to PHP, you can see that I write <?=$redirect_to?> as the value of the hidden field. That is the shorthand version to write PHP code which has the same meaning as <?php echo $redirect_to; ?>. Additionally you can also see an @ symbol before the variable name. This is used to surpress error messages (i.e. if we use/print the variable while it is unset).

3. The Login Process.

When a user clicks Login button, all the above data are sent to login_submit.php. In this file, we check for the username/password pair. If they match then the login is successful and we can go back to the last page. Otherwise the login form is displayed again with an error message.

For this example we will just check that user must enter “admin” as his username and password.

login_submit.php

<?php
// Get form inputs
$username = $_POST[‘username’];
$password = $_POST[‘password’];
$redirect_to = $_POST[‘redirect_to’];// Check login credentials
if($username == ‘admin’ && $password == ‘admin’) {
// Success
session_start();
$_SESSION[‘is_logged_in’] = true;

// If the last page is known, redirect to last page,
// otherwise go to home page.
if($redirect_to != ”)
header(‘Location: ‘.$redirect_to);
else
header(‘Location: index.php’);
}
else {
// When failure, reload the login form
$error = “Invalid username/password”;
include(‘login.php’);
}
?>

Sometimes $_SERVER[‘HTTP_REFERER’] (or the $redirect_to variable in this case) may not contain any data. This event may occur when users are directly going to the login page by typing the URL in the address bar, for example. So we still need to check that if $redirect_to is empty, we just go to the homepage (index.php) as usual.

4. Bonus: The Logout Process.

So far, our login page tutorial should be finished here. But it’s not complete if we don’t also create the logout page. So as a bonus, here’s the code for logout.php.

logout.php

<?php
// Get the refering page
$redirect_to = $_SERVER[‘HTTP_REFERER’];// Destroy session (logout)
session_start();
session_destroy();

// If the last page is known, redirect to last page,
// otherwise go to home page.
if($redirect_to != ”)
header(‘Location: ‘.$redirect_to);
else
header(‘Location: index.php’);
?>

The easiest way to logout is by destroying the session, so all the data inside $_SESSION will be cleared.

When users logout, we might also want them to return to their last visited page, so there we also check for $redirect_to variable. This goes the same way as the one in login_submit.php file.

Hope this tutorial helps! 🙂

» Download all the files here.