Using Session Variables for Login Security

 

Introduction.  Since session variables exist for the duration of a session we can require a user to login through a page and set a session variable if they do so appropriately.  All other pages in the site can have a code snippet at the very beginning that will redirect the user back to the login page if they haven't completed it correctly and try to bypass it.

To illustrate this we will need three pages.

  • a login form
  • a processing page that will
    • test for the correctness of the password
    • set a session variable if it is correct
    • redirect the user back if the login is incorrect and
    • send them onto the index page if it is correct
  • an index page that contains a code snippet at the very beginning that tests whether the session variable has been set
    • redirect the user to the login page if it is not correct
    • allow access to the page if it is correct

The first page should be called site_login.php.

 

<html>
<head>
<title>Login Page for the Site</title>
</head>

<body bgcolor="003044" text="cccccc">
<form action="site_login_processing.php" method = "post">
<table width=500>
<tr>
<td align=center colspan=2><h3Please enter the password</h3></td>
</tr>
<tr>
<td align=right><b>Password: </b></td>
<td><input type="password" name="txt_password", size=10></td>
</tr>
<tr>
<td align=center colspan=2><input type="submit" name="cmd_submit" value = "Submit Password"></td>
</tr>
</table>
</form>
</body>
</html>

 

Now we need the processing page.  The user is not likely to even see this page.  You should call it  site_login_processing.php.

 

<?php
// obtaining the information from the form and
// using it to determine redirection

if ($txt_password != "letmein")
{

header("location:site_login.php");

}
else
{

session_start( );
$_SESSION["valid_user"] = "valid";
header("location:site_index.php");

}
?>
<html>
<head>
<title>Directing the User Based on a Password</title>
</head>

<body>
</body>
</html>

 

Notice how the if - else structure depends on the user's input and does certain things based on its value.

The last page in our trio is a very pared down index page that does little more than test for the presence of the session variable $_SESSION["valid_user"].  You should call this page site_index.php.

 

<?php
// checking to see whether the user has
// entered a valid password

session_start();
if ($_SESSION["valid_user"] != "valid")
{

header("location:site_login.php");

}
?>
<html>
<head>
<title>Directing the User Based on a Password</title>
</head>

<body bgcolor="003044" text="cccccc">
<h2>An Index Page</h2>
</body>
</html>

 

This sort of PHP code segment needs to be placed at the beginning of every other page within the web to ensure the user has the valid password.