User Registration and Login System in CodeIgniter


User Login System is the most required feature in CodeIgniter framework. CodeIgniter provides many built-in libraries and helpers for implementing user authentication system. We can easily implement the user registration and login system with the session in CodeIgniter. In this tutorial, we’ll provide a step-by-step guide to building a login system in CodeIgniter with session and MySQL database.

We assume that you have already known the configuration process of CodeIgniter framework. If you are new to CodeIgniter, we suggest to checkout this CodeIgniter beginners guide first – CodeIgniter Beginners Guide – Configuration and Setup

The following functionalities will be implemented in our example CodeIgniter Login System script.

  • The user registration page to submit the user details and insert it into the MySQL database.
  • The user login page for sign in.
  • Login and registration form validation.
  • Existing email check during registration.
  • Store logged in user identification into session.
  • Display user account details after login.
  • Logout the user from their account.

Before you begin to implement user registration and login system in CodeIgniter, take a look at the files and folder structure.

codeigniter-user -login-system-files-folders-structure-codexworld

Database Table Creation

To store the user account information, a table is required in the database. The following SQL creates a users table into the MySQL database with some basic required fields.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `gender` enum('Male','Female') COLLATE utf8_unicode_ci NOT NULL,
 `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config (autoload.php)

In this CodeIgniter Login System script, some built-in system libraries and helpers are used. So, open the application/config/autoload.php file and load those libraries and helpers.

$autoload['libraries'] = array('session','database');
$autoload['helper'] = array('url','form');

Controller (Users.php)

The Users controller handles all the user login related works. The used functions and their functionality are given below.
__construct() – Form validation library and user model is loaded.
account() – Displays user account details after login.
login() – Displays login form and sign in to the user account if valid credentials are given.
registration() – Displays user registration form and insert user account information into the database once submit.
logout() – Logouts users from their account.
email_check() – checks whether given email already exists in the database.
CodeIgniter built-in form validation library is used in login() and registration() to ensure that the user submits all the required fields.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * User Management class created by CodexWorld
 */
class Users extends CI_Controller {
    
    function 
__construct() {
        
parent::__construct();
        
$this->load->library('form_validation');
        
$this->load->model('user');
    }
    
    
/*
     * User account information
     */
    
public function account(){
        
$data = array();
        if(
$this->session->userdata('isUserLoggedIn')){
            
$data['user'] = $this->user->getRows(array('id'=>$this->session->userdata('userId')));
            
//load the view
            
$this->load->view('users/account'$data);
        }else{
            
redirect('users/login');
        }
    }
    
    
/*
     * User login
     */
    
public function login(){
        
$data = array();
        if(
$this->session->userdata('success_msg')){
            
$data['success_msg'] = $this->session->userdata('success_msg');
            
$this->session->unset_userdata('success_msg');
        }
        if(
$this->session->userdata('error_msg')){
            
$data['error_msg'] = $this->session->userdata('error_msg');
            
$this->session->unset_userdata('error_msg');
        }
        if(
$this->input->post('loginSubmit')){
            
$this->form_validation->set_rules('email''Email''required|valid_email');
            
$this->form_validation->set_rules('password''password''required');
            if (
$this->form_validation->run() == true) {
                
$con['returnType'] = 'single';
                
$con['conditions'] = array(
                    
'email'=>$this->input->post('email'),
                    
'password' => md5($this->input->post('password')),
                    
'status' => '1'
                
);
                
$checkLogin $this->user->getRows($con);
                if(
$checkLogin){
                    
$this->session->set_userdata('isUserLoggedIn',TRUE);
                    
$this->session->set_userdata('userId',$checkLogin['id']);
                    
redirect('users/account/');
                }else{
                    
$data['error_msg'] = 'Wrong email or password, please try again.';
                }
            }
        }
        
//load the view
        
$this->load->view('users/login'$data);
    }
    
    
/*
     * User registration
     */
    
public function registration(){
        
$data = array();
        
$userData = array();
        if(
$this->input->post('regisSubmit')){
            
$this->form_validation->set_rules('name''Name''required');
            
$this->form_validation->set_rules('email''Email''required|valid_email|callback_email_check');
            
$this->form_validation->set_rules('password''password''required');
            
$this->form_validation->set_rules('conf_password''confirm password''required|matches[password]');

            
$userData = array(
                
'name' => strip_tags($this->input->post('name')),
                
'email' => strip_tags($this->input->post('email')),
                
'password' => md5($this->input->post('password')),
                
'gender' => $this->input->post('gender'),
                
'phone' => strip_tags($this->input->post('phone'))
            );

            if(
$this->form_validation->run() == true){
                
$insert $this->user->insert($userData);
                if(
$insert){
                    
$this->session->set_userdata('success_msg''Your registration was successfully. Please login to your account.');
                    
redirect('users/login');
                }else{
                    
$data['error_msg'] = 'Some problems occured, please try again.';
                }
            }
        }
        
$data['user'] = $userData;
        
//load the view
        
$this->load->view('users/registration'$data);
    }
    
    
/*
     * User logout
     */
    
public function logout(){
        
$this->session->unset_userdata('isUserLoggedIn');
        
$this->session->unset_userdata('userId');
        
$this->session->sess_destroy();
        
redirect('users/login/');
    }
    
    
/*
     * Existing email check during validation
     */
    
public function email_check($str){
        
$con['returnType'] = 'count';
        
$con['conditions'] = array('email'=>$str);
        
$checkEmail $this->user->getRows($con);
        if(
$checkEmail 0){
            
$this->form_validation->set_message('email_check''The given email already exists.');
            return 
FALSE;
        } else {
            return 
TRUE;
        }
    }
}

Model (User.php)

The User model is used to fetch and insert the user data. getRows() function fetch the user data from the database and insert() function insert the user account data to the database.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class 
User extends CI_Model{
    function 
__construct() {
        
$this->userTbl 'users';
    }
    
/*
     * get rows from the users table
     */
    
function getRows($params = array()){
        
$this->db->select('*');
        
$this->db->from($this->userTbl);
        
        
//fetch data by conditions
        
if(array_key_exists("conditions",$params)){
            foreach (
$params['conditions'] as $key => $value) {
                
$this->db->where($key,$value);
            }
        }
        
        if(
array_key_exists("id",$params)){
            
$this->db->where('id',$params['id']);
            
$query $this->db->get();
            
$result $query->row_array();
        }else{
            
//set start and limit
            
if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
                
$this->db->limit($params['limit'],$params['start']);
            }elseif(!
array_key_exists("start",$params) && array_key_exists("limit",$params)){
                
$this->db->limit($params['limit']);
            }
            
$query $this->db->get();
            if(
array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
                
$result $query->num_rows();
            }elseif(
array_key_exists("returnType",$params) && $params['returnType'] == 'single'){
                
$result = ($query->num_rows() > 0)?$query->row_array():FALSE;
            }else{
                
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
            }
        }

        
//return fetched data
        
return $result;
    }
    
    
/*
     * Insert user information
     */
    
public function insert($data = array()) {
        
//add created and modified data if not included
        
if(!array_key_exists("created"$data)){
            
$data['created'] = date("Y-m-d H:i:s");
        }
        if(!
array_key_exists("modified"$data)){
            
$data['modified'] = date("Y-m-d H:i:s");
        }
        
        
//insert user data to users table
        
$insert $this->db->insert($this->userTbl$data);
        
        
//return the status
        
if($insert){
            return 
$this->db->insert_id();;
        }else{
            return 
false;
        }
    }

}

View (users/)

To integrate CodeIgniter login system, 3 view files are used, registration.php, login.php, and account.php.

Registration Form (users/registration.php)
This file contains form HTML to collect the user account information. Once the user submits the form, it is submitted to the registration() method of Users controller.

<!DOCTYPE html>
<html lang="en">  
<head>
<link href="<?php echo base_url(); ?>assets/css/style.css" rel='stylesheet' type='text/css' />
</head>
<body>
<div class="container">
    <h2>User Registration</h2>
    <form action="" method="post">
        <div class="form-group">
            <input type="text" class="form-control" name="name" placeholder="Name" required="" value="<?php echo !empty($user['name'])?$user['name']:''?>">
          <?php echo form_error('name','<span class="help-block">','</span>'); ?>
        </div>
        <div class="form-group">
            <input type="email" class="form-control" name="email" placeholder="Email" required="" value="<?php echo !empty($user['email'])?$user['email']:''?>">
          <?php echo form_error('email','<span class="help-block">','</span>'); ?>
        </div>
        <div class="form-group">
            <input type="text" class="form-control" name="phone" placeholder="Phone" value="<?php echo !empty($user['phone'])?$user['phone']:''?>">
        </div>
        <div class="form-group">
          <input type="password" class="form-control" name="password" placeholder="Password" required="">
          <?php echo form_error('password','<span class="help-block">','</span>'); ?>
        </div>
        <div class="form-group">
          <input type="password" class="form-control" name="conf_password" placeholder="Confirm password" required="">
          <?php echo form_error('conf_password','<span class="help-block">','</span>'); ?>
        </div>
        <div class="form-group">
            <?php
            
if(!empty($user['gender']) && $user['gender'] == 'Female'){
                
$fcheck 'checked="checked"';
                
$mcheck '';
            }else{
                
$mcheck 'checked="checked"';
                
$fcheck '';
            }
            
?> <div class="radio"> <label> <input type="radio" name="gender" value="Male" <?php echo $mcheck?>> Male </label> </div> <div class="radio"> <label> <input type="radio" name="gender" value="Female" <?php echo $fcheck?>> Female </label> </div> </div> <div class="form-group"> <input type="submit" name="regisSubmit" class="btn-primary" value="Submit"/> </div> </form> <p class="footInfo">Already have an account? <a href="<?php echo base_url(); ?>users/login">Login here</a></p> </div> </body> </html>

Login Form (users/login.php)
This file contains login form HTML to authenticate the user with their account. Once the user submits the form, it is submitted to the login() method of Users controller.

<!DOCTYPE html>
<html lang="en">  
<head>
<link href="<?php echo base_url(); ?>assets/css/style.css" rel='stylesheet' type='text/css' />
</head>
<body>
<div class="container">
    <h2>User Login</h2>
    <?php
    
if(!empty($success_msg)){
        echo 
'<p class="statusMsg">'.$success_msg.'</p>';
    }elseif(!empty(
$error_msg)){
        echo 
'<p class="statusMsg">'.$error_msg.'</p>';
    }
    
?> <form action="" method="post"> <div class="form-group has-feedback"> <input type="email" class="form-control" name="email" placeholder="Email" required="" value="">            <?php echo form_error('email','<span class="help-block">','</span>'); ?> </div> <div class="form-group"> <input type="password" class="form-control" name="password" placeholder="Password" required="">           <?php echo form_error('password','<span class="help-block">','</span>'); ?> </div> <div class="form-group"> <input type="submit" name="loginSubmit" class="btn-primary" value="Submit"/> </div> </form> <p class="footInfo">Don't have an account? <a href="<?php echo base_url(); ?>users/registration">Register here</a></p> </div> </body> </html>

User Account (users/account.php)
If user’s login is successful, this view is loaded with the account details of the respective user.

<!DOCTYPE html>
<html lang="en">  
<head>
<link href="<?php echo base_url(); ?>assets/css/style.css" rel='stylesheet' type='text/css' />
</head>
<body>
<div class="container">
    <h2>User Account</h2>
    <h3>Welcome <?php echo $user['name']; ?>!</h3>
    <div class="account-info">
        <p><b>Name: </b><?php echo $user['name']; ?></p>
        <p><b>Email: </b><?php echo $user['email']; ?></p>
        <p><b>Phone: </b><?php echo $user['phone']; ?></p>
        <p><b>Gender: </b><?php echo $user['gender']; ?></p>
    </div>
</div>
</body>
</html>

Conclusion

This CodeIgniter user authentication tutorial will help you to implement simple login system in CodeIgniter. Also, you can easily extend our CodeIgniter login system script as per your requirement.

Recommended Tutorials For You

5 Comments

  1. Floyd Said...
    • CodexWorld Said...
  2. Hetal Said...
    • CodexWorld Said...
  3. Dinesh Krishnan Said...

Leave a reply

CONNECT WITH CODEXWORLD