Filling our toolbox

We will now create a file that will contain the functions needed for our authentication system. When a user registers we will need to make sure that the username and email that they picked are not already in use. We will also need to send them an email with the password that we randomly generated for them. When a user logs in we update the last login column in the database table to to reflect that time. This file will hold all the functions needed by our individual system pages, keeping all database queries in this one file.

File: authUtils.php

<?php

// function for generating a random password
function randPassword() {
   $password = "";
 
   for ($x = 1; $x <= 8; $x++) {
      switch ( rand(1, 3) ) {
 
      //  Add a random digit, 0-9
      case 1:
      $password .= rand(0, 9);
      break;
 
      //  Add a random upper-case letter
      case 2:
      $password .= chr( rand(65, 90) );
      break;
 
      //  Add a random lower-case letter
      case 3:
      $password  .= chr( rand(97, 122) );
      break;
      }
   }
 
   return $password;
}

// function for updating login time
function updateUserLogin($username){
    global $dbc;
    $sql = "UPDATE " . USERS_TABLE . " set last_login = now() where " . USER_COLUMN . "='$username' LIMIT 1";
    $r = mysqli_query($dbc,$sql) ;

    return mysqli_affected_rows($dbc) == 1;
}

// function for checking if a username exists
function usernameExists($username){
     global $dbc;
     $sql = "SELECT COUNT(*) from " . USERS_TABLE . " WHERE ". USER_COLUMN . "='$username'";
     $res = mysqli_query($dbc, $sql);

     $num = mysqli_fetch_row($res);

     return  $num[0] == 1;
}

// function for checking if an email address exists
function emailExists($email){
     global $dbc;
     $sql = "SELECT COUNT(*) FROM " . USERS_TABLE . " WHERE email='$email'";
     $res = mysqli_query($dbc, $sql);

     $num = mysqli_fetch_row($res);

     return  $num[0] == 1;
}

// Other code

Here we define the function for generating a random password that we can send to the user and save in a hashed format in our database. Then we define the function we will use to update the database each time a user successfully logs in. Then we define 2 functions to check whether or not a requested username or email already exists in our database. Notice that we are using the constants defined in our config file where possible, and that to have access to the $dbc variable from within our functions we need to prefix it with "global".

File authUtils.php(cont.)

// Other Code
function validUserCredentials($data = array()) {
    global $dbc;
    $md5Password = md5($data['password']);
    $sql = "SELECT COUNT(*) FROM " . USERS_TABLE . " WHERE " . USER_COLUMN . "='$data[username]' AND password='$md5Password'";
    $res = mysqli_query($dbc, $sql);
   
    $num = mysqli_fetch_row($res);
   
    return $num[0] == 1;
}

// function for loading user data
function loadUserData($username) {
     global $dbc;
     $sql = "SELECT * from " . USERS_TABLE . " where " . USER_COLUMN . "='$username'";
     $res = mysqli_query($dbc, $sql);
      
     $user = mysqli_fetch_array($res, MYSQLI_ASSOC);
      
     return $user;
}

// function for loading user data by email address
function loadByEmail($email) {
     global $dbc;
     $sql = "SELECT * from " . USERS_TABLE . " WHERE email='$email'";
     $res = mysqli_query($dbc, $sql);
      
     $user = mysqli_fetch_array($res, MYSQLI_ASSOC);
      
     return $user;
}

// Other code

Here we define functions for validating the users login form entries, this way we can proceed from within our code with a simple conditional. We then define 2 functions for loading user data, one by the username for when the user signs in and he other by the email address for when the user forgets their username or password and needs to have them sent to them.

File: authUtils.php(cont.)

// Other code

// function for reseting password
function updatePassword($email, $md5Password){
    global $dbc;
    $sql = "UPDATE " . USERS_TABLE . " SET password='$md5Password' where email='$email' LIMIT 1";
    $res = mysqli_query($dbc, $sql);
   
    if (mysqli_affected_rows($dbc) == 1){
        return true;
    } else {
        return false;
    }
}

// function for adding a user to the database
function addNewUser($data = array()) {
     global $dbc;
     $sql = "INSERT INTO " . USERS_TABLE . " (username, email, password, first_name, last_name) VALUES ('$data[username]', '$data[email]', '" . md5($data['password']) . "', '$data[first_name]', '$data[last_name]')";
     $res = mysqli_query($dbc, $sql);

     if (mysqli_affected_rows($dbc) != 1) {
          return false;
     } else {
          return true;
     }
}

// function to send user registration confirmation email
function sendRegisterEmail($data = array()) {
    $to = $data['email'];
    $subject = "Registration with " . SITE_NAME;
    $message = "Your login details are as follows:<br />Username: $data[username]<br />Password: $data[password]<br />";
    $message .= "You can log into your account <a href=\"http://" . SITE_URL ."/login.php\">here!</a><br />";

    $headers = "MIME-Version: 1.0\n";
    $headers .="Content-type: text/html; charset-ISO-8859-1r\n";
    $headers .= "from:".SITE_CONTACT."";
   
    // for local testing output message to screen by uncommenting following line
    // echo "$to<br />$subject<br />$message<br />$headers<br />";

    if (mail($to, $subject, $message, $headers)) {
         return true;
    } else {
         return false;
    }
}
?>

Finally we create a function to update the users password when they request to have it reset, one to add a new user to our database and a function to send an email when they register or reset their password. This should give us all the tools to carry out the basic functions of a user registration and authentication system. Next we will look at how to start using these tools and build the rest of our system