Logging in with Sessions

Creating a basic password protected area can be such a usefull tool on your website, but learning how to use sessions effectively can be difficult. I hope that by the end of this tutorial you’ll know all you need to know to get your own password protected area up and running.

The login.php Code
The following code should be used to create the login.php file, which will be where users are sent to if they are not logged in correctly.

<?
session_start();
session_register("spassword");
if ($action == "login") {
    $spassword = $password;
    Header("Location: protected.php\n\n");
    exit();
}
?>
Please login below:
<FORM METHOD=POST ACTION="login.php">
<INPUT TYPE=HIDDEN NAME="action" VALUE="login">
<INPUT TYPE=PASSWORD NAME="password">
<INPUT TYPE=SUBMIT VALUE="Login"></FORM>

The code is pretty simple. Before you can use sessions you must turn session handling on, and register the variables you wish to use. session_register can handle multiple variables at a time, just put a comma in between them. Notice the variable names are without the $ and in quotes.

The next section checks if the user submitted the form by seeing if the hidden variable is set. If it is, it then sets the session variable to the inputted password. Note that if I didn’t do this, the session variable would still be blank even if the form used the same variable name.

It then redirects the user to the protected page, which will use the code below.

The protected.php Code
This page is the page you’ll want protected. All the content would go after the PHP code, and you could make multiple copies of this page to make multiple pages that require a login.

<?
$thepw = "SECRET";

session_start();
session_register("spassword");
if ($spassword != $thepw) {
    Header("Location: login.php\n\n");
    exit();
}
?>

This code is incredibly simple. It just turns sessions on again, registers spassword as the session variable (I use spassword so the s reminds me that it is in a session – not inputted by a form). It then checks if this variable holds the same text as the configured password ($thepw) and if not redirects to the login page.

Remember: It is important you use the exit(); function here to make PHP stop sending output after the location change. This is because users could setup their browser to not change location and view the page as it continues to be outputted.

Simply put your page below that PHP end tag. Whatever is there will only be visible if the user logged in with the correct password.