User Authentication

User authentication on a web page generally means typing in a username and a password. The script compares the details entered with information stored on the server before deciding whether or not to grant access.

This example will use passwords hard-coded into its scripts. This is not something we would ever want to do in a published web site but useful for us to focus only on the key functionality for authenticating users on our sites.

We will need a handful of files to make this process work. It's often easier to use some includes to keep the main scripts tidy.

When you create these files, place them all in a single folder for ease of access in this demonstration.

login_form.inc

<!-- form for user login -->
<h1>Password Please</h1>
<form action="login.php?do=login" method="post">
<h2>Username</h2>
<p><input type="text" name="fusername" size="30" maxsize="30"></p>
<h2>Password</h2>
<p><input type="password" name="fpassword" size="30" maxsize="30"></p>
<p><input type="submit" value="Enter"></p>
</form>

The names of the text boxes start with an 'f'. I do this with all variables on forms. In PHP, the source of information can matter, particularly when considering security. The extra letter reminds the programmer of this.

login.php

<?php
// start the session - even if they are not logged in
session_start();

// HTML page header
echo '<html>
<head>
<title>Password Please</title>
</head>
<body>';

// if the user has submitted the form
if (isset($_GET['do']))
{
   // get form data
   $fuser = $_POST['fusername'];
   $fpass = $_POST['fpassword'];
   // hard-coded password comparison
   if ($fuser=='me' && $fpass=='letmein')
   {
      // successful
      // set session variable to keep track of the user
      $_SESSION['uname'] = $fuser;
      // another session variable to store whether or not the user is authenticated
      $_SESSION['auth'] = "yes";
      echo "<h1>Welcome</h1>";
      echo "<p><a href='secret.php'>Go To The Secret Page</a></p>";
   }
   else
   {
      // naughty
      echo "<h1>Security Breach - Fetch The Feds</h1>";
      echo "<p>Either you can't spell your own name or you aren't allowed on the site.</p>";
      require("login_form.inc");
   }
}
// form not yet submitted, show login form
else
{
   require("login_form.inc");
}

// HTML page footer
echo "</body></html>";
?>

Read the comments in the script to see what each section does. The default view of the page is encoded in the last 'else' clause - just shows the login form. If the user has tried to login, a comparison is made with the credentials that were expected. If they pass the check, some session variables are assigned values. These variables will be available to PHP scripts later on. Finally, the user is presented with a hyperlink to a page that requires an authenticated user.

sesh.inc

<?php
session_start();
if (!isset($_SESSION['auth'] ) OR $_SESSION['auth']!= "yes")
{
    // Make a basic page
   echo '<html>
   <head>
   <title>Password Please</title>
   </head>
   <body>
   <h1>Oh dear</h1>
   <p>Authorised users only.</p>
   </body>
   </html>';
   // kill the rest of the PHP
   exit();
}
?>

This script is the doorperson for all of your pages which require authentication. It looks to see if the user has logged in and kills the intended scripts if they are not.

secret.php

<?php
require("sesh.inc");
// HTML page header
echo '<html>
<head>
<title>Password Please</title>
</head>
<body>';
// find out the username of the authenticated user
$them = $_SESSION['uname'];
echo "<p>Welcome to the secret world, ".$them."</p>";
echo "<p><a href='logout.php'>Logout</a></p>";
echo "</body></html>";
?>

The first line of the script must be to run the code in the sesh.inc file. Provided that the user is logged in, the secret page should be displayed. Notice also that you can access the session variables that you set when they login.

logout.php

<?php
require("sesh.inc");
session_unset();
session_destroy();
echo '<html>
<head>
<title>Password Please</title>
</head>
<body>
<h1>Goodbye</h1>
<p>Session over.</p>
</body></html>';
?>

This final script is needed to allow users to logout of the program. Once you have clicked on the link on the secret page, refreshing the page should result in being denied access to the secure content.

There are a few changes you can make to this group of scripts to learn a little more,

You could change or add usernames and passwords to the login script. For example, make two arrays (one of usernames, one of passwords). This would allow you to adapt the information on the page to specific users.

You can spend some time checking what exactly kills the session. For example, login and go to the secret page. Then type a URL in the address bar and visit some other web pages. Type in the address of the secret page and see if the session still holds. You can also find out whether closing a tab, but leaving the browser open kills the session and whether or not a session persists if the browser is closed and reopened. And this leads on to the next point,

Security

You use a password to reliably identify specific users and deliver content appropriate to them. When you are using client-side scripting like the Javascript examples on this site, any script commands are interpreted by the client computer. PHP statements are executed on the server. This means that care must be taken when processing form data.

This page deals only with the basic principles of the session.

Doing Some More

You can store arrays as session variables. An interesting little project would be to make something a bit like a shopping cart.

You could make a simple turn-based combat system where character attributes persist between pages.