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.
Example : basic/login.php
Source : basic/login.phps
// ... we will put some php code here
?>
if ($errorMessage != '') {
?>
}
?>
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.
Example : basic/login.php
Source : basic/login.phps
// 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 (
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
Example : basic/main.php
Source : basic/main.phps
// 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;
}
?>
This is the main application page. You are free to play around here since you
are an autenthicated user :-)
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 :
Example : basic/logout.php
Source : basic/logout.phps
// 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.
A more common method of authenticating a user is by checking the database to see if the submitted user id and password combination exist. To use this kind of authentication we must first build the database table. The sql code to build it is shown below. We also add two user accounts for testing the login script
Source : database/tbl_auth_user.sql
CREATE TABLE tbl_auth_user (
user_id VARCHAR(10) NOT NULL,
user_password CHAR(32) NOT NULL,
PRIMARY KEY (user_id)
);
INSERT INTO tbl_auth_user (user_id, user_password) VALUES ('theadmin', PASSWORD('chumbawamba'));
INSERT INTO tbl_auth_user (user_id, user_password) VALUES ('webmaster', PASSWORD('webmistress'));
We will use the same html code to create login form created in previous example. We will only need to modify the login process a bit. The login script's content is shown below :
Example : database/login.php
Source : database/login.phps
// we must never forget to start the session
session_start();
$errorMessage = '';
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
include 'library/config.php';
include 'library/opendb.php';
$userId = $_POST['txtUserId'];
$password = $_POST['txtPassword'];
// check if the user id and password combination exist in database
$sql = "SELECT user_id
FROM tbl_auth_user
WHERE user_id = '$userId'
AND user_password = PASSWORD('$password')";
$result = mysql_query($sql)
or die('Query failed. ' . mysql_error());
if (mysql_num_rows($result) == 1) {
// the user id and password match,
// set the session
$_SESSION['db_is_logged_in'] = true;
// after login we move to the main page
header('Location: main.php');
exit;
} else {
$errorMessage = 'Sorry, wrong user id / password';
}
include 'library/closedb.php';
}
?>
// ... same html login form as previous example
Instead of checking the user id and password against a hardcoded info we query the database if these two exist in the database using the SELECT query. If we found a match we set the session variable and move to the main page. Note that the session name is prefixed by 'db_' to make it different than the previous example.
For the next two scripts ( main.php and logout.php ) the code is similar to previous one. The only difference is the session name. Here is the code for these two
Example : database/main.php
Source : database/main.phps
session_start();
// is the one accessing this page logged in or not?
if (!isset($_SESSION['db_is_logged_in'])
|| $_SESSION['db_is_logged_in'] !== true) {
// not logged in, move to login page
header('Location: login.php');
exit;
}
?>
// ... some html code here
Example : database/logout.php
Source : dabase/logout.phps
session_start();
// if the user is logged in, unset the session
if (isset($_SESSION['db_is_logged_in'])) {
unset($_SESSION['db_is_logged_in']);
}
// now that the user is logged out,
// go to login page
header('Location: login.php');
?>
No comments:
Post a Comment