A Multi-User Login System

The simple user login system created previously is very limited. The only way to add a user is to add their username and password to the code of the "login.php" file. It would be far easier if the website administrator could add new users to the system using a simple form rather than having to add a new line of code to the "login.php" file for each new user. If there are going to be a large number of users accessing the protected areas of your website, it is far more practical to store the users' credentials in a database. Of course, we will have to create the database, and the administrator will need special privileges in order to be able to add users to the database. He or she will require access to a web page that allows new user details to be entered on a simple form. Let's start by creating the database.

  1. Connect to the MySQL server, open a command window, and navigate to the directory where MySQL stores its executable files (on my computer, this would be X:\xampp\mysql\bin\), and enter the command:

    mysql -u root

  2. Enter the following command to create the "admin" database:

    create database admin;

  3. Tell MySQL which database you want to use:

    use admin;

  4. Enter the following commands to create the table "user":

    CREATE TABLE user
    (
      userID int not null auto_increment,
      primary key(userID),
      username varchar(20) not null,
      password varchar(20) not null
    );

  5. Create the admin user:

    insert into user (username, password) values ("admin", "letmein");

We now have to amend the login page to query the database to check whether the username and password entered by a user are valid, rather than simply relying on a set of hard-coded values. The revised code is shown below.

<?php
  $user = "";
  $pass = "";
  $validated = false;

  if ($_POST)
  {
    $user = $_POST['username'];
    $pass = $_POST['password'];
  }

  session_start();
  $_SESSION['login'] = "";
  if($user!="" && $pass!="")
  {
    $conn = @mysql_connect ("localhost", "root", "") or die ("Sorry - unable to connect to MySQL database.");
    $rs = @mysql_select_db ("admin", $conn) or die ("error");
    $sql = "SELECT * FROM user WHERE username = '$user' AND password = '$pass'";
    $rs = mysql_query($sql,$conn);
    $result = mysql_num_rows($rs);

    if ($result > 0) $validated = true;
    if($validated)
    {
      $_SESSION['login'] = "OK";
      $_SESSION['username'] = $user;
      $_SESSION['password'] = $pass;
      header('Location: protected.php');
    }
    else
    {
      $_SESSION['login'] = "";
      echo "Invalid username or password.";
    }
  }
  else $_SESSION['login'] = "";
?>

<html>
  <head>
    <title>Login Page</title>
  </head>

  <body>
    <h1>Login Page</h1>
    <p>Please enter your username and password:</p>
    <form action="login.php" method="post">
      <table>
        <tr>
          <td align="right">Username: </td>
          <td><input size=\"20\" type="text" size="20" maxlength="15" name="username"></td>
        </tr>
        <tr>
          <td align="right">Password: </td>
          <td><input size=\"20\" type="password" size="20" maxlength="15" name="password"></td>
        </tr>
        <tr>
          <td> </td>
          <td colspan="2" align="left"><input type="submit" value="Login"></td>
        </tr>
      </table>
    </form>
  </body>
</html>

Note that initially, only the admin user will be able to login to the protected page. The application will look exactly the same as in the previous example, with one exception. When the admin user logs in, a link will be displayed within the protected web page that allows them to go to another web page in order to create additional users. The code for "protected.php" will therefore change slightly, as shown below.

<?php
  session_start();
  if($_SESSION['login'] != "OK")
  {
    header('Location: login.php');
    exit();
  }
?>

<html>

  <head>
    <title>Protected Web Page</title>
  </head>

  <body>
    <h1>Protected Web Page</h1>

  <?php
    echo "<p>You have successfully logged in!</p>";
    echo "<p>Your username is: ";
    echo $_SESSION['username'];
    echo "<br>";
    echo "Your password is: ";
    echo $_SESSION['password'];
    echo "</p>";

    if($_SESSION['username'] == 'admin')
    {
      echo "<p><a href='create_user.php'>Create a new user</a></p>";
    }
  ?>

  </body>

</html>



The output from the amended version of protected.php

The output from the amended version of protected.php


The user creation page will present the admin user with a simple form (similar to the login page itself) that allows him or her to enter a username and a password for the new user. The code for the user creation page is shown below, together with a screenshot of its output, and should be saved as "create_user.php".

<?php

  session_start();
  if($_SESSION['login'] != "OK")
  {
    header('Location: login.php');
    exit();
  }
?>

<html>
<head>
  <title>Create User</title>
</head>

<body>

<h1>Create a new user</h1>

<p>Please enter details for the new user:</p>

<form action="insert_user.php" method="post">
  <table>
    <tr>
      <td align="right">Username: </td>
      <td><input size=\"20\" type="text" size="20" maxlength="15" name="new_username"></td>
    </tr>
    <tr>
      <td align="right">Password: </td>
      <td><input size=\"20\" type="password" size="20" maxlength="15" name="new_password"></td>
    </tr>
    <tr>
      <td> </td>
      <td colspan="2" align="left"><input type="submit" value="Create user"></td>
    </tr>
  </table>
</form>
</body>
</html>




The output from create_user.php

The output from create_user.php


When the admin user clicks on the "submit" button, a further script ("insert_user.php") will be called that inserts the new user details into the database. The script creates a page that either tells the admin user that the new user details have been successfully added to the database or reports an error in the case of failure. The admin user is then given the option of returning to the protected page or logging out of the application. Once a user has been successfully created, they should be able to log into the application (note that they will not be presented with the option of creating a new user - only the admin user has access to the "Create a new user" link). Here is the code for "insert_user.php":

<html>
<head>
  <title>Insert User</title>
</head>

<body>

<h1>User Creation</h1>

<?php

  session_start();
  if($_SESSION['login'] != "OK")
  {
    header('Location: login.php');
    exit();
  }

  $new_user = $_POST["new_username"];
  $new_pass = $_POST["new_password"];
  $conn = @mysql_connect ("localhost", "root", "") or die ("Sorry - unable to connect to MySQL database.");
  $rs = @mysql_select_db ("admin", $conn) or die ("error");
  $sql = "INSERT INTO user (username, password) VALUES ('$new_user', '$new_pass')";
  mysql_query($sql,$conn) or die ("User creation failed.");
  echo "<p>User created successfully.</p>";
  echo "<p>Return to <a href='protected.php'>application</a> or <a href='login.php'>log out</a></p>";
?>
</body>
</html>

The output from "insert_user.php" is illustrated below.


The output from insert_user.php

The output from insert_user.php