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
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 :
// 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
<?php
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
<?php
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');
?>




