-
-
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'));
-
Copy code
We will use the same html code to create the login form created in the above example. We just need to modify the login process a little bit.
Login script:
-
-
- // 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';
- < ;p> $userId = $_POST['txtUserId'];
- $password = $_POST['txtPassword'];
// Check that the user id and password combination exists in the 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) {
- // sessionthe sets the user id and password to match,
- // sets the session
- $_SESSION['db_is_logged_in'] = true;
// After logging in we go to the homepage
- header('Location: main.php');
- exit;
- } else {
- $ errorMessage = 'Sorry, wrong user id / password';
- }
include 'library/closedb.php';
- }
- ?>
-
Copy code
/ /…Same html login form as the previous example
Instead of checking the user id and password against hardcoded information we query the database and use a SELECT query if these two exist in the database. If we find a match we set the session variable and move to the home page. Note that the session name is prefixed with "db" making it different from the previous example.
The code in the next two scripts (main.php and logout.php) is similar to the previous one. The only difference is the session name. Here is the code for both
-
-
- session_start();
//Is it a login to visit this page?
- if (!isset($_SESSION[' db_is_logged_in'])
- || $_SESSION['db_is_logged_in'] !== true) {
// No login, return to the login page
- header('Location: login.php') ;
- exit;
- }
?>
-
Copy code
/ /…some html code here
-
-
- session_start();
// If the user is logged in, set the session
- if (isset($_SESSION['db_is_logged_in '])) {
- unset($_SESSION['db_is_logged_in']);
- }
// Now, the user is logged in,
- // Go to the login page
- header('Location: login. php');
- ?>
-
Copy code
|