User Registration and Login System in CodeIgniter

User Login System is the most used feature in CodeIgniter application. Like the user authentication in PHP, the user login system can be easily implemented in CodeIgniter with the session. CodeIgniter framework provides many built-in libraries and helpers which helps to integrate registration and login functionality with MySQL database.

The login system is very useful to restrict access to your application. This feature allows only the logged-in user to access web pages of your web application. You can easily implement the user authentication system (registration and login) with the session in CodeIgniter application. In this step-by-step tutorial, we will show you how to build a login system in CodeIgniter with SESSION and MySQL database.

Hope you have already know the configuration process of the CodeIgniter framework. If you are new to CodeIgniter, we suggest to see this CodeIgniter beginners guide first – CodeIgniter Beginners Guide with Configuration and Setup

The following functionality will be implemented in the example CodeIgniter Login System script.

  • The user registration form to provide the account information.
  • Insert account data into the MySQL database.
  • The user login form 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 structure.

codeigniter_login_system/
├── application/
│   ├── controllers/
│   │   └── Users.php
│   ├── models/
│   │   └── User.php
│   └── views/
│       ├── elements/
│       │   ├── header.php
│       │   └── footer.php
│       └── users/
│           ├── registration.php
│           ├── login.php
│           └── account.php
└── assets/
    └── css/
        └── style.css

Create Database Table

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

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `password` varchar(200) 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` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Config (autoload.php)

In this CodeIgniter Login System script, the built-in system library and helper are used. Define the frequently used libraries and helpers in the application/config/autoload.php file.

// Auto-load Libraries 
$autoload['libraries'] = array('database''session');

// Auto-load Helper Files
$autoload['helper'] = array('url');

Controller (Users.php)

The Users controller handles the user registration and authentication-related operations.

  • __construct()
    • Load the Form validation library and User model.
    • Get the user’s login status from SESSION.
  • index() – Based on the login status redirects the user to the account/login page.
  • account()
    • Get the logged-in user’s account information using getRows() method of User model.
    • Pass user data and load the account details view.
  • login()
    • Initially, load the login form view.
    • If the form is submitted,
      • Validate the posted fields data using CodeIgniter Form Validation library.
      • Check whether the user exists in the database with the provided login credentials.
      • Based on the login status redirects the user to account/login page.
  • registration()
    • Initially, load the registration form view.
    • If the form is submitted,
      • Validate the posted fields data using CodeIgniter Form Validation library.
      • Check whether the provided email already exists in the database using a custom callback function (email_check).
      • Insert the user’s account information in the database using insert() method of the User model.
  • logout() – Log the user out from their account.
  • email_check() – Custom callback function used with CodeIgniter form validation library to check the existing email.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 

class 
Users extends CI_Controller {
    
    function 
__construct() {
        
parent::__construct();
        
        
// Load form validation ibrary & user model
        
$this->load->library('form_validation');
        
$this->load->model('user');
        
        
// User login status
        
$this->isUserLoggedIn $this->session->userdata('isUserLoggedIn');
    }
    
    public function 
index(){
        if(
$this->isUserLoggedIn){
            
redirect('users/account');
        }else{
            
redirect('users/login');
        }
    }

    public function 
account(){
        
$data = array();
        if(
$this->isUserLoggedIn){
            
$con = array(
                
'id' => $this->session->userdata('userId')
            );
            
$data['user'] = $this->user->getRows($con);
            
            
// Pass the user data and load view
            
$this->load->view('elements/header'$data);
            
$this->load->view('users/account'$data);
            
$this->load->view('elements/footer');
        }else{
            
redirect('users/login');
        }
    }

    public function 
login(){
        
$data = array();
        
        
// Get messages from the session
        
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 login request submitted
        
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 = array(
                    
'returnType' => 'single',
                    
'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.';
                }
            }else{
                
$data['error_msg'] = 'Please fill all the mandatory fields.';
            }
        }
        
        
// Load view
        
$this->load->view('elements/header'$data);
        
$this->load->view('users/login'$data);
        
$this->load->view('elements/footer');
    }

    public function 
registration(){
        
$data $userData = array();
        
        
// If registration request is submitted
        
if($this->input->post('signupSubmit')){
            
$this->form_validation->set_rules('first_name''First Name''required');
            
$this->form_validation->set_rules('last_name''Last 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(
                
'first_name' => strip_tags($this->input->post('first_name')),
                
'last_name' => strip_tags($this->input->post('last_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 account registration has been successful. Please login to your account.');
                    
redirect('users/login');
                }else{
                    
$data['error_msg'] = 'Some problems occured, please try again.';
                }
            }else{
                
$data['error_msg'] = 'Please fill all the mandatory fields.';
            }
        }
        
        
// Posted data
        
$data['user'] = $userData;
        
        
// Load view
        
$this->load->view('elements/header'$data);
        
$this->load->view('users/registration'$data);
        
$this->load->view('elements/footer');
    }
    
    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 = array(
            
'returnType' => 'count',
            
'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 handles the database related operations (fetch and insert).

  • getRows() – Fetch the user data from the database based on the conditions.
  • insert() – Insert the user account data in the database.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 

class 
User extends CI_Model{
    function 
__construct() {
        
// Set table name
        
$this->table 'users';
    }
    
    
/*
     * Fetch user data from the database
     * @param array filter data based on the passed parameters
     */
    
function getRows($params = array()){
        
$this->db->select('*');
        
$this->db->from($this->table);
        
        if(
array_key_exists("conditions"$params)){
            foreach(
$params['conditions'] as $key => $val){
                
$this->db->where($key$val);
            }
        }
        
        if(
array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
            
$result $this->db->count_all_results();
        }else{
            if(
array_key_exists("id"$params) || $params['returnType'] == 'single'){
                if(!empty(
$params['id'])){
                    
$this->db->where('id'$params['id']);
                }
                
$query $this->db->get();
                
$result $query->row_array();
            }else{
                
$this->db->order_by('id''desc');
                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();
                
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
            }
        }
        
        
// Return fetched data
        
return $result;
    }
    
    
/*
     * Insert user data into the database
     * @param $data data to be inserted
     */
    
public function insert($data = array()) {
        if(!empty(
$data)){
            
// Add created and modified date 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 member data
            
$insert $this->db->insert($this->table$data);
            
            
// Return the status
            
return $insert?$this->db->insert_id():false;
        }
        return 
false;
    }
}

View

1. elements/
This directory holds the element parts of the web pages.

1.1. elements/header.php
This file holds the header part of the web pages.

<!DOCTYPE html>
<html lang="en">  
<head>
<title>CodeIgniter User Login System by CodexWorld</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900" 	type="text/css" media="all">

<!-- Stylesheet file -->
<link href="<?php echo base_url('assets/css/style.css'); ?>" rel='stylesheet' type='text/css' />
</head>
<body>

<h1>CODEIGNITER USER LOGIN SYSTEM BY CODEXWORLD</h1>

1.2. elements/footer.php
This file holds the footer part of the web pages.

</body>
</html>

2. users/
This directory holds the view files of the user login system.

2.1. users/registration.php

  • This view file is used to display the registration form.
  • 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.
<div class="container">
    <h2>Create a New Account</h2>
	
    <!-- Status message -->
    <?php  
        
if(!empty($success_msg)){
            echo 
'<p class="status-msg success">'.$success_msg.'</p>';
        }elseif(!empty(
$error_msg)){
            echo 
'<p class="status-msg error">'.$error_msg.'</p>';
        }
    
?> <!-- Registration form --> <div class="regisFrm"> <form action="" method="post"> <div class="form-group"> <input type="text" name="first_name" placeholder="FIRST NAME" value="<?php echo !empty($user['first_name'])?$user['first_name']:''?>" required> <?php echo form_error('first_name','<p class="help-block">','</p>'); ?> </div> <div class="form-group"> <input type="text" name="last_name" placeholder="LAST NAME" value="<?php echo !empty($user['last_name'])?$user['last_name']:''?>" required> <?php echo form_error('last_name','<p class="help-block">','</p>'); ?> </div> <div class="form-group"> <input type="email" name="email" placeholder="EMAIL" value="<?php echo !empty($user['email'])?$user['email']:''?>" required> <?php echo form_error('email','<p class="help-block">','</p>'); ?> </div> <div class="form-group"> <input type="password" name="password" placeholder="PASSWORD" required> <?php echo form_error('password','<p class="help-block">','</p>'); ?> </div> <div class="form-group"> <input type="password" name="conf_password" placeholder="CONFIRM PASSWORD" required> <?php echo form_error('conf_password','<p class="help-block">','</p>'); ?> </div> <div class="form-group"> <label>Gender: </label>                 <?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> <label> <input type="radio" name="gender" value="Female" <?php echo $fcheck?>> Female </label> </div> </div> <div class="form-group"> <input type="text" name="phone" placeholder="PHONE NUMBER" value="<?php echo !empty($user['phone'])?$user['phone']:''?>"> <?php echo form_error('phone','<p class="help-block">','</p>'); ?> </div> <div class="send-button"> <input type="submit" name="signupSubmit" value="CREATE ACCOUNT"> </div> </form> <p>Already have an account? <a href="<?php echo base_url('users/login'); ?>">Login here</a></p> </div> </div>

2.2. users/login.php

  • This view file is used to display the login form.
  • 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.
<div class="container">
    <h2>Login to Your Account</h2>
	
    <!-- Status message -->
    <?php  
        
if(!empty($success_msg)){
            echo 
'<p class="status-msg success">'.$success_msg.'</p>';
        }elseif(!empty(
$error_msg)){
            echo 
'<p class="status-msg error">'.$error_msg.'</p>';
        }
    
?> <!-- Login form --> <div class="regisFrm"> <form action="" method="post"> <div class="form-group"> <input type="email" name="email" placeholder="EMAIL" required=""> <?php echo form_error('email','<p class="help-block">','</p>'); ?> </div> <div class="form-group"> <input type="password" name="password" placeholder="PASSWORD" required=""> <?php echo form_error('password','<p class="help-block">','</p>'); ?> </div> <div class="send-button"> <input type="submit" name="loginSubmit" value="LOGIN"> </div> </form> <p>Don't have an account? <a href="<?php echo base_url('users/registration'); ?>">Register</a></p> </div> </div>

2.3. users/account.php
This view displays the account details of the logged-in user.

<div class="container">
    <h2>Welcome <?php echo $user['first_name']; ?>!</h2>
    <a href="<?php echo base_url('users/logout'); ?>" class="logout">Logout</a>
    <div class="regisFrm">
        <p><b>Name: </b><?php echo $user['first_name'].' '.$user['last_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>

CodeIgniter CRUD Operations with Search and Pagination

Conclusion

This simple user authentication script helps you to implement the login system in CodeIgniter. The login script can be used for many purposes where user authentication is needed. You can easily enhance the functionality of our CodeIgniter login system script as per your needs.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

41 Comments

  1. Kamlesah Said...
  2. John Said...
  3. Tom Said...
  4. Fatih Said...
  5. Arnav Anand Said...
  6. Reets Said...
  7. Khalid Said...
  8. Paras Said...
  9. Sana Said...
    • CodexWorld Said...
  10. Sana Said...
    • CodexWorld Said...
  11. Marc Said...
    • CodexWorld Said...
  12. Ajith Said...
  13. Jolina Rose Said...
  14. Gaurav Said...
    • CodexWorld Said...
  15. Arif Said...
    • CodexWorld Said...
  16. Saintlight Said...
  17. Saintlight Said...
    • CodexWorld Said...
  18. Gary Said...
  19. Eric Rosenberg Said...
    • CodexWorld Said...
  20. Lokesh Said...
    • CodexWorld Said...
  21. Bhavin Said...
  22. Sya Said...
  23. Kevin Fonseca Said...
  24. Jyoti Rajgond Said...
  25. Vkdewangga Said...
    • CodexWorld Said...
  26. Floyd Said...
    • CodexWorld Said...
  27. Hetal Said...
    • CodexWorld Said...
  28. Dinesh Krishnan Said...

Leave a reply

keyboard_double_arrow_up