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. For this reason, the login form can’t use the same single-script approach as in register.php. The question then becomes: where should the user end up when he successfully logs in and when he doesn’t? In both cases, I decided the user should end up back on the home page; for this reason, the login form gets submitted to index.php. Hence, the index page needs to be updated with the code for handling the form. Rather than writing that code directly into the home page, it’s better to include it as a separate file, just after the database connection but prior to the inclusion of the header file:


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

Processing the Form

I think it will be easier to follow the login process if I talk about the form last, so let’s first look at the code that handles the login form. That process needs to do the following in this order:

  1. Validate the submitted email address and password.
  2. Compare the submitted values with those in the database.
  3. Define 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 = escape_data($_POST['email'], $dbc);
    } 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 = $_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. However, 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, pass, IF(date_expires >= NOW(), true, false) AS expired FROM users WHERE email='$e'";
       $r = mysqli_query($dbc, $q);

    The basic query selects five values from the users table: the user’s ID, username, type, password, and account expiration. The WHERE clause checks that the email address matches the submitted email address. The password will be checked in the PHP code.

    For the account expiration, I’m doing something that may be new to you. I don’t care when the user’s account expires, only whether 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:

    if (mysqli_num_rows($r) === 1) {
       $row = mysqli_fetch_array($r, MYSQLI_ASSOC);

    This conditional will be true if the email address exists in the database.

  7. Compare the password against the stored password:

    if (password_verify($p, $row['pass'])) {

    This code was explained at the beginning of the chapter, and it lets you verify a submitted password against a stored one. Again, you’ll need to include the password_compat library before this line if you’re using a version of PHP prior to 5.5.

  8. If the user is an administrator, create a new session ID, just to be safe:

    if ($row['type'] === 'admin') {
       $_SESSION['user_admin'] = true;

    If the user is an administrator, two things must be done. First, the session identifier ought to be changed as a security measure. Doing so prevents session fixation attacks (where a hacker sets a user’s session ID to match the hacker’s own session ID, then gets the administrator to log in, thereby giving the hacker administrative authority). The session_regenerate_id() function serves this purpose.

    Next, I only want to create a $_SESSION['user_admin'] element with a true value if the user’s type equals admin. Understand that I don’t want to create a $_SESSION['user_admin'] element equal to false if the user’s 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.

  9. Store the other data in the session:

    $_SESSION['user_id'] = $row['id'];
    $_SESSION['username'] = $row['username'];
    if ($row['expired'] === 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.

    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['expired'] (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.

  10. If the password didn’t match, or if no database row was returned, create an error message:

       } else {
          $login_errors['login'] = 'The email address and password do not match those on file.';
    } else {
       $login_errors['login'] = 'The email address and password do not match those on file.';

    The same error message will be used if the user supplied a valid email address but the password didn’t match that stored in the database, or if the email address wasn’t found in the database at all. 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.

  11. 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.

  12. Save the file.

Creating the Form

The next script to discuss,, is 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 fourth 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.

Here’s the complete

if (!isset($login_errors)) $login_errors = array();
<form action="index.php" method="post" accept-charset="utf-8">
if (array_key_exists('login', $login_errors)) {
   echo '<div class="alert alert-danger">' . $login_errors['login'] . '</div>';
create_form_input('email', 'email', '', $login_errors, array('placeholder'=>'Email address'));
create_form_input('pass', 'password', '', $login_errors, array('placeholder'=>'Password'));
<button type="submit" class="btn btn-default">Login &rarr;</button>

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 results 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.8). Other error messages are associated with the offending form input (Figure 4.9).

Figure 4.8

Figure 4.8

Figure 4.9

Figure 4.9

  • + Share This
  • 🔖 Save To Your Account