Php Codeigniter Login Script with Server Side Validation

Php Codeigniter Login Script with Server Side Validation

By Yashwant Chavan, Views 27079, Date 28-Nov-2014

Are you developing user authentication using php codeigniter? Then this tutorial is going to teach you how to build a simple login form with codeigniter.

tags php php-codeigniter login-script php-validation

In below tutorial, I am going to touch upon login and logout functionality along with server side validation using php codeigniter validation rules. I hope below steps will be helpful in better understanding.

Popular Codeigniter Tutorials

Tools and Technologies

The very first step is to get the all required software`s and technologies. Once we have Php and XAMPP installed, we can start creating a simple php codeigniter application. This time I am using Php codeigniter version 2.2 which is bit different with earlier version of codeigniter 1.7

  1. Php Codeigniter 2.2
  2. XAMPP / Php 5.2.3
  3. Mysql 5.0.4

Database table trn_user

Lets create trn_user table with the help of below mysql table script.

CREATE TABLE  `technicalkeeda`.`trn_user` (
  `user_id` int(10) unsigned NOT NULL auto_increment,
  `user_name` varchar(150) collate latin1_general_ci NOT NULL,
  `password` varchar(100) collate latin1_general_ci NOT NULL,
  `first_name` varchar(45) collate latin1_general_ci NOT NULL,
  `last_name` varchar(45) collate latin1_general_ci NOT NULL,
  PRIMARY KEY  (`user_id`)
);

Here I am going to insert one user record in trn_user table. which we are going to validate using username and password.

 INSERT INTO `trn_user` (`user_id`,`user_name`,`password`,`first_name`,`last_name`) VALUES 
 (1,'yashwantchavan','demo','Yashwant','Chavan');
codeigniter user login example eclipse setup

Codeigniter Database Configuration

As you know that Php Codeigniter is popular for its minimum configuration (almost Zero configuration). To connect database you need to provide username, password and other db configuration details in database.php file.

The config file is located at "application/config/database.php". Below are my local mysql database setting, you can it as per your db details.

 $active_group = 'default';
 $active_record = TRUE;

 $db['default']['hostname'] = 'localhost';
 $db['default']['username'] = 'root';
 $db['default']['password'] = '';
 $db['default']['database'] = 'technicalkeeda';
 $db['default']['dbdriver'] = 'mysql';
 $db['default']['dbprefix'] = '';
 $db['default']['pconnect'] = TRUE;
 $db['default']['db_debug'] = TRUE;
 $db['default']['cache_on'] = FALSE;
 $db['default']['cachedir'] = '';
 $db['default']['char_set'] = 'utf8';
 $db['default']['dbcollat'] = 'utf8_general_ci';
 $db['default']['swap_pre'] = '';
 $db['default']['autoinit'] = TRUE;
 $db['default']['stricton'] = FALSE;

Codeigniter Base Url Configuration

$config['base_url'] = "http://localhost/codeigniterexamples";

Codeigniter route Configuration

I have defined some routing rules for different URLS in routes.php file, which is located under directory application/config/

$route['default_controller'] = "user";
$route['404_override'] = '';

$route['login'] = "/user/login";
$route['logout'] = "/user/logout";
$route['signin'] = "/user/signin";
$route['successpage'] = "/user/successpage";

User Controller (user.php)

Lets creates the Controller class called User under directory name application/controllers

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller{

 public function __construct(){
  parent::__construct();
  $this->load->model('UserModel');
  $this->load->library(array('form_validation','session'));
  $this->load->helper(array('url','html','form'));
 }

 public function index(){
  $this->login();
 }


 public function login(){
  $this->load->view('login');
 }

 public function successpage(){
  $this->load->view('successpage');
 }

 function logout(){
  $this->session->sess_destroy();
  redirect(base_url());
 }


 function signin(){

  $userName= trim($this->input->post('userName'));
  $password= trim($this->input->post('password'));

  $query = $this->UserModel->processLogin($userName,$password);


  $this->form_validation->set_rules('userName', 'Username', 'required|callback_validateUser[' . $query->num_rows() . ']');
  $this->form_validation->set_rules('password', 'Password', 'required');

  $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
  $this->form_validation->set_message('required', 'Enter %s');

  if ($this->form_validation->run() == FALSE) {
   $this->load->view('login');
  }else{
   if($query){
    $query = $query->result();
    $user = array(
     'USER_ID' => $query[0]->USER_ID,
     'USER_NAME' => $query[0]->USER_NAME,
     'EMAIL' => $query[0]->EMAIL,
     'FIRST_NAME' => $query[0]->FIRST_NAME,
     'LAST_NAME' => $query[0]->LAST_NAME
    );

    $this->session->set_userdata($user);
    redirect('index.php/successpage');
   }
  }
 }

 /** Custom Validation Method*/
 public function validateUser($userName,$recordCount){
  if ($recordCount != 0){
   return TRUE;
  }else{
   $this->form_validation->set_message('validateUser', 'Invalid %s or Password');
   return FALSE;
  }
 }
}

Define Php Codeigniter Validation Rules

Load form_validation library $this->load->library(array('form_validation','session')); before use any validation specific API. Once the library is loaded define validation rules. I have defined core required and custom callback_validateUser validation rules.

 $this->form_validation->set_rules('userName', 'Username', 'required|callback_validateUser[' . $query->num_rows() . ']');
 $this->form_validation->set_rules('password', 'Password', 'required');

Customise Error Messages

You can customise default error messages as per your need, below are some examples

$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_message('required', 'Enter %s');
$this->form_validation->set_message('validateUser', 'Invalid %s or Password');

User Model (usermodel.php)

Lets create the Model class and define processLogin() method, which will query the trn_user table and validate the user with the help of username and password.

<?php
class UserModel extends CI_Model {

 function __construct(){
  parent::__construct();
 }

 function processLogin($userName=NULL,$password){
  $this->db->select("USER_ID,USER_NAME,FIRST_NAME,LAST_NAME");
  $whereCondition = $array = array('USER_NAME' =>$userName,'PASSWORD'=>$password);
  $this->db->where($whereCondition);
  $this->db->from('TRN_USER');
  $query = $this->db->get();
  return $query;
 }

}
?>

login.php

Lets create login.php file under folder name application/views. Which contains the login form along with username and password text field. Once the user submit the login form to user controller, It will perform the login functionality.

Here I have displayed <?php echo form_error('userName'); ?> and <?php echo form_error('password'); ?> field specific error messages, which is displayed whenever any validation rule violated.

<!DOCTYPE html>
<html lang="en">
<head>
    <link href="<?= base_url();?>css/bootstrap.css" rel="stylesheet">
    <style>
     .error{
      color:red;
     }
    </style>
</head>    
<body>
 <div class="container">
     <div class="row">
         <div class="col-md-6">
             <div class="row">
                 <div class="col-md-12">
                     <h3>Login In</h3>
                  <form method="post" action="http://localhost/codeigniterexamples/index.php/signin">                                             
                      <div class="form-group">                       
                       <label for="userName">Username</label> <input type="text" class="form-control" id="userName" name="userName" value="<?php echo set_value('userName'); ?>">
                       <?php echo form_error('userName'); ?>                       
       </div>
       
       <div class="form-group">
        <label for="password"> Password </label> <input type="password" class="form-control" id="password" name="password" value="<?php echo set_value('password'); ?>"> 
        <?php echo form_error('password'); ?>
        
       </div>
                   
                   <button class="btn btn-success" type="submit">Login</button>
      
      </form>
     </div>
             </div>
         </div>               
     </div>
 </div>        
</body>
</html> 

successpage.php

<!DOCTYPE html>
<html lang="en">
 <head>
    <link href="<?= base_url();?>css/bootstrap.css" rel="stylesheet">
    </head>
    <body>
    <div class="container">
            <div class="row">
               <div class="col-md-6">
                 <div class="row">
                  <div class="col-md-12">
                      <h3>Login Successful <?=$this->session->userdata('FIRST_NAME')?> <?=$this->session->userdata('LAST_NAME')?></h3>
                      <a href="<?= base_url();?>index.php/logout">Logout</a>                                               
                     </div>
                   </div>
                </div>               
            </div>
  </div>        
    </body>
</html>
 

Run

Enter the url http://localhost/codeigniterexamples in your browser, It will display the Login page

Codeigniter Login Page Screen 2

Verify mandatory field value validation.

Codeigniter Login Page Validation Screen

Verify the custom validation, Enter wrong username and password, It will display the respected error message.

Codeigniter Login Page custom Validation Screen

Enter the valid username and password, which we have inserted into trn_user table. You will get the success page.

codeigniter user login success page
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]