With this basic authentication method we store the user information ( user id
and password ) directly in the script. This is only good if the application
only have one user since adding more user means we must also add the new user id
and password in the script.
Let's start by making the login form first. You can see the code below.
<?php
// ... we will put some php code here
?>
<html>
<head>
<title>Basic Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
if ($errorMessage != '') {
?>
<p align="center"><strong><font color="#990000"><?php
echo $errorMessage; ?></font></strong></p>
<?php
}
?>
<form method="post" name="frmLogin"
id="frmLogin">
<table width="400" border="1" align="center"
cellpadding="2" cellspacing="2">
<tr>
<td width="150">User Id</td>
<td><input name="txtUserId" type="text"
id="txtUserId"></td>
</tr>
<tr>
<td width="150">Password</td>
<td><input name="txtPassword" type="password"
id="txtPassword"></td>
</tr>
<tr>
<td width="150"> </td>
<td><input type="submit" name="btnLogin" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
Nothing sophisticated in that form. It's just a basic login form with two
input for entering the user id and password. Make sure that the form method
is set to post since we certainly don't want to show up the
user id and password in the address bar.
Right before the login form we there's a code for printing an error message.
We can ignore this for now since we'll be talking about it shortly.
Once we submit the form we can start the authentication process. We simply
check if the user id and password exist in $_POST and check if these two
match the hardcoded user id and password.
<?php
// we must never forget to start the session
session_start();
$errorMessage = '';
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword']))
{
// check if the user id and password combination is correct
if ($_POST['txtUserId'] === 'theadmin' && $_POST['txtPassword']
=== 'chumbawamba') {
// the user id and password match,
// set the session
$_SESSION['basic_is_logged_in'] = true;
// after login we move to the main page
header('Location: main.php');
exit;
} else {
$errorMessage = 'Sorry, wrong user id / password';
}
}
?>
// ... here is the login form shown previously
But before we start matching the user id and password. We must
start the session first. Never forget to start the session before doing anything
to the session since it won't work.
You can see above that the hardcoded user id and password are "theadmin"
and "chumbawamba". If the submitted user id and password match
these two then we set the value of $_SESSION['basic_is_logged_in']
to true. After that we move the application's main page. In this case it's
called main.php
If the user id and password don't match we set the error message. This
message will be shown on top of the login form.
Note : When starting the session you may stumble upon this
kind of error :
Warning: session_start(): Cannot send session cache
limiter - headers already sent (output started at C:\Webroot\examples\user-authentication\basic\login.php:1)
in C:\Webroot\examples\user-authentication\basic\login.php on line 3
PHP will spit this error message if the script that call session_start()
already send something ( a blank space, newline, etc ). The error above happen
when i add a single space on the first line right before
the php opening tag ( <?php ). Thankfully the error message shows where
the output started so fixing this kind of error is simple. After removing
that extra space the error is fixed.
Checking if the user is logged in or not
Since the application main page, main.php, can only be accessed by those
who already authenticated themselves we must check that before displaying
the page.
The checking process is fairly simple. We just see if $_SESSION['basic_is_logged_in']
is set or not. If it is set we check if the value is true.
If either of this condition is not met then the one accessing this page haven't
login yet. And so we redirect to the login page and quit the script.
If $_SESSION['basic_is_logged_in'] is set and
it's value is true then we can continue showing
the rest of the page.
Here is the code for main.php
<?php
// like i said, we must never forget to start the session
session_start();
// is the one accessing this page logged in or not?
if (!isset($_SESSION['basic_is_logged_in'])
|| $_SESSION['basic_is_logged_in'] !== true) {
// not logged in, move to login page
header('Location: login.php');
exit;
}
?>
<html>
<head>
<title>Main User Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<p>This is the main application page. You are free to play around here
since you
are an autenthicated user :-) </p>
<p> </p>
<p><a href="logout.php">Logout</a> </p>
</body>
</html>
A little note about naming a session variable. As you can see the session
that we used to mark whether a user is logged in or not is named 'basic_is_logged_in'.
When setting a name for a session variable it's a good thing to use
the application name as the prefix. In this case the prefix is
'basic_' . This is especially important when you have multiple
application on one site where each requires different
login information.
For example, suppose we have a cms application and a link exchange application
where each have their own user authentication system. In both application
we use the session variable $_SESSION['is_logged_in'].
In this case if we already logged in in the cms application we will no longer
be required to login in the link exchange application since both are using
the same session name. This is usually not an intended feature.
To avoid that kind of thing we can instead use $_SESSION['cms_is_logged_in']
and $_SESSION['exchange_is_logged_in']
The Logout Script
No login script is complete without the logout script right? So let's start
making the logout script now.
The process of logging out a user is actually depends on how we check if
a user is logged in or not. In our case we check if $_SESSION['basic_is_logged_in']
is already set or not and check whether it's value is true. Using this
information we can build the logout script to simply unset this session or
set the session value to false.
The logout script below use the first method ( unset the session ). Here
is the code :
<?php
// i will keep yelling this
// DON'T FORGET TO START THE SESSION !!!
session_start();
// if the user is logged in, unset the session
if (isset($_SESSION['basic_is_logged_in'])) {
unset($_SESSION['basic_is_logged_in']);
}
// now that the user is logged out,
// go to login page
header('Location: login.php');
?>
Before we unset the session we first check if the session is actually exist
or not. In case you access the logout script before using the login form then
this session variable won't exist yet.
Unsetting a variable is done simply by using the unset()
statement. After we unset the session the next thing we do is simply moving
to the login page. Pretty simple huh ?
Another note : You may already notice this but in each
script i keep repeating about not to forget to start the session. The reason
is that it is a very very very common error to forget about it when handling
session. Once i spent a lot of time debugging a script and it was all because
i forgot to add that one line.