Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Logging In

Logging in to the site is a two-step process: completing the form and validating the submitted values against the database. The login form is not its own page—it's shown in the sidebar to all non-logged-in users, so it cannot use the same single-script approach as in register.php . The question, then, was where the user should end up when they do successfully log in and when they don't. In both cases, I decided they should end up back on the home page; for this reason, the login form gets submitted to index.php . Therefore, the index page needs to be updated with the code for handling the form. Rather than write that code directly into the home page, it's best included as a separate file, just after the database connection but prior to the inclusion of the header file:

    include ('./includes/login.php');

This works because normally index.php will be requested via GET. If it's a POST request, the login form has been submitted, so this script includes the file that will test the login credentials.

Processing the Form

I think it will actually be easier to follow the login process if I talk about the form last, so let's look at the code that handles the login form first. That process needs to:

  1. Validate the submitted email address and password.
  2. Compare the submitted values with those in the database.
  3. Create errors if the values are incorrect.
  4. Store data in a session if the values are correct.

Here's how all of that works in actual code:

  1. Create a new PHP script in your text editor or IDE to be named

    This will be stored in the includes directory.

  2. Create an empty array for recording errors:

    $login_errors = array();

    This errors array will be used just like $reg_errors in the registration script.

  3. Validate the email address:
    if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $e = mysqli_real_escape_string ($dbc, $_POST['email']);
    } else {
        $login_errors['email'] = 'Please enter a valid email address!';

    This code replicates that in the registration process, using PHP's Filter extension to validate the email address.

  4. Validate the password:
    if (!empty($_POST['pass']) ) {
        $p = mysqli_real_escape_string ($dbc, $_POST['pass']);
    } else {
        $login_errors['pass'] = 'Please enter your password!';

    To validate the password, I'm just making sure it's not empty. Part of the reason is performance—this will be faster than the zero-width positive lookahead regular expression used in the registration process—and part of the reason will be explained later in the chapter.

    In theory, you don't need to validate the submitted values because the database query will be confirming whether the submitted values are correct or not, but database queries are expensive (in terms of server resources and performance), so it's best not to run one unless necessary.

  5. If there are no errors, query the database:

    if (empty($login_errors)) {
        $q = "SELECT id, username, type, IF(date_expires > NOW(), true,
        false) FROM users WHERE (email='$e' AND pass='" . get_password_hash($p) . "')";
        $r = mysqli_query ($dbc, $q);

    The basic query selects four values from the users table: their ID, username, type, and account expiration. The WHERE clause checks that the email address matches the submitted email address and that the password matches the hashed version of the password.

    For the account expiration, I'm doing something that may be new to you. I don't really care when the user's account expires, only if it's valid right now. One way of accomplishing this would be to select the expiration value, which is a date, and then use PHP to convert it into a timestamp and compare it to the current timestamp. That's a lot of code and logic to put onto PHP. Instead, I'm doing an IF conditional within my MySQL query. That syntax is just:

    IF(date_expires >= NOW(), true, false)

    The first expression is the condition being tested; the second is what's returned if the condition is true; the third value is what's returned if the condition is false. Thus, if the expiration date is greater than or equal to this moment, the value true will be selected.

  6. If one row was returned by the database query, fetch the data and store it in a session:

    if (mysqli_num_rows($r) == 1) {
        $row = mysqli_fetch_array ($r, MYSQLI_NUM);
        $_SESSION['user_id'] = $row[0];
        $_SESSION['username'] = $row[1];
        if ($row[2] == 'admin') $_SESSION['user_admin'] = true;
        if ($row[3] == 1) $_SESSION['user_not_expired'] = true;

    First, the user's ID and name are stored in the session, but given user< something > names, so that they won't possibly conflict later on with anything else I might store in the session.

    To indicate that the user is an administrator, I only want to create a $_SESSION['user_admin'] element if the user's type equals admin. I don't want to create a $_SESSION['user_admin'] element equal to false if their type is member. This is because the function that will validate a user's access to pages— redirect_invalid_user() in —will check only if a session variable is set, not what its actual value is.

    For the expiration, I only want to store a value indicating that the account hasn't expired. MySQL will return the number 1 for the Boolean value true , so if $row[3] (which is the value in the array for the expiration status) equals that, I create a new element in $_SESSION . Again, I'm not assigning a value if the account has expired.

  7. If no row was returned, create an error message:
    } else {
        $login_errors['login'] = 'The email address and password do not 
         match those on file.';

    This error message will apply if the user supplied a valid email address and a password but the values didn't match those stored in the database. For security purposes, the script doesn't indicate which of the two values is incorrect, or if the email address has been registered at all.

  8. Complete the script:
    } // End of $login_errors IF.

    As with all other scripts that will be included by other scripts, I'm omitting the closing PHP tag.

  9. Save the file.

Creating the Form

The last script to discuss,, is actually the first step in the process. It needs to do just two things: present a form and report any errors that occurred when the form was submitted. The form contains two inputs: one for the email address and one for the password. Both are created using the same create_form_input() function, which means that the script must be included. The function needs to take an array of errors—$login_errors—as its third argument. That array is created in However, if the user is just loading the login form for the first time, $login_errors won't exist, so this script should initialize an empty array in that case. As a second complication, on the register.php and forgot_password.php pages, the script will already have been included, making require_once() the appropriate way to include that file here.

Here's the complete


 1  <?php
 2  if (!isset($login_errors)) $login_errors = array();
 3  require_once ('./includes/');
 4  ?><div class="title">
 5    <h4>Login</h4>
 6  </div>
 7  <form action="index.php" method="post" accept-charset="utf-8">
 8  <p><?php if (array_key_exists('login', $login_errors)) {
 9    echo '<span class="error">' . $login_errors['login'] . '</span><br />';
10  }?><label for="email"><strong>Email Address</strong></label>
    <br /><?php create_form_input('email', 'text', $login_errors); ?>
    <br /><label for="pass"><strong>Password</strong></label>
    <br /><?php create_form_input('pass', 'password', $login_errors); ?>
    <a href="forgot_password.php" align="right">Forgot?</a><br />
    <input type="submit" value="Login &rarr"></p>
11  </form>

Just before the email address label, you'll see this code:

<?php if (array_key_exists('login', $login_errors)) {
echo '<span class="error">' . $login_errors['login'] . '</span><br />';

By default, all errors are reported via the create_form_input() function. However, this form is a bit different in that could create an error (that is, an element in the $login_errors array) not associated with a particular form input. That error occurs when both fields are properly filled out but the values don't, together, match a record in the database. In that case, the $login_errors['login'] element is assigned an error message. Therefore, the form first checks if that array element exists in $login_errors , in which case the error message will be displayed just before the two inputs (Figure 4.12). Other error messages are associated with the offending form input (Figure 4.13).

After you've done all this, you can now test the login process.

  • + Share This
  • 🔖 Save To Your Account