Codeigniter Login and Registration Tutorial & Source Code

On 6/24/2016

Today we'll see a codeigniter tutorial demonstrating user login and registration system. As you know Login and Signup Module (User Management System) forms the base for membership driven websites and applications. I have written about codeingiter login and registration process separately earlier, but got requests from blog readers to provide a complete user management module. So in today's post, I have tried to cover as much as possible in user module comprising home, login, signup and user profile/dashboard page.

So let us see how to create complete codeigniter login and registration system.

Create Database for CI Login & Signup Module:

First create the mysql database required for the codeigniter user management system.

CREATE DATABASE `testdb`;
USE `testdb`;

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `fname` varchar(30) NOT NULL,
  `lname` varchar(30) NOT NULL,
  `email` varchar(60) NOT NULL,
  `password` varchar(40) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Run the above the sql commands in mysql db and create the necessary database and table.

Build CodeIgniter Login and Registration System:

To build our codeigniter login and registration system we need a bunch of controller, view and model files. Here are the files we are going to create.

  • home.php - This is the Home page controller of the user management application.
  • login.php - It's the user login form controller file.
  • signup.php - This one is the user signup page(registration) controller.
  • profile.php - This is the controller for my profile/dashboard page.
  • home_view.php - It is the Home page view file.
  • login_view.php - View file for login controller.
  • signup_view.php - View file for signup/registration controller.
  • profile_view.php – It is the user profile view file.
  • user_model.php - This is the model file for the user management module. Here we place all the db transactions of the module.

Also Read: CodeIgniter Database CRUD Example

Codeignitor User Login and Registration System:

In case you don't know, below are the steps breakdown for what we are going to build in this user login/signup system in code igniter.

  1. The user enters the Home page which contains links for Login and Signup on top navigation menu.
  2. As for New Users » user click on Signup link » user redirected to signup/registration form » user fills up the form details and submit » process user details and store it into database » notify user.
  3. As for Registered Users » user click on the Login link on Home page » user redirected to login form » user enter login credentials » authenticate user and redirect to User Profile page.
  4. For Singed-in users » Show User's name and Logout link on top menu bar.
  5. When user clicks on Logout » destroy session and redirect to Home page.

Note: As for designing user interface, I have used the readily available Twitter Bootstrap CSS as it's easier this way and mobile responsive in nature. Check here to know about using bootstrap with codeigniter framework.

Home.php

This is controller for the Home/Main page of the user management module and it shows Login and Signup link at the top menu for guests and User's Name and Logout link for signed-in users.

<?php
class home extends CI_Controller
{
 public function __construct()
 {
  parent::__construct();
  $this->load->helper(array('url', 'html'));
  $this->load->library('session');
 }
 
 function index()
 {
  $this->load->view('home_view');
 }
 
 function logout()
 {
  // destroy session
        $data = array('login' => '', 'uname' => '', 'uid' => '');
        $this->session->unset_userdata($data);
        $this->session->sess_destroy();
  redirect('home/index');
 }
}
?>

Signup.php

This is the controller file for the codeigniter user registration form. It collects first name, last name, email id and password from the user and validates the input and stores it into database.

<?php
class signup extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
        $this->load->library(array('session', 'form_validation'));
        $this->load->database();
        $this->load->model('user_model');
    }

    function index()
    {
        // set form validation rules
        $this->form_validation->set_rules('fname', 'First Name', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
        $this->form_validation->set_rules('lname', 'Last Name', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
        $this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email|is_unique[user.email]');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|matches[cpassword]|md5');
        $this->form_validation->set_rules('cpassword', 'Confirm Password', 'trim|required');

        // submit
        if ($this->form_validation->run() == FALSE)
        {
            // fails
            $this->load->view('signup_view');
        }
        else
        {
            //insert user details into db
            $data = array(
                'fname' => $this->input->post('fname'),
                'lname' => $this->input->post('lname'),
                'email' => $this->input->post('email'),
                'password' => $this->input->post('password')
            );

            if ($this->user_model->insert_user($data))
            {
                $this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Successfully Registered! Please login to access your Profile!</div>');
                redirect('signup/index');
            }
            else
            {
                // error
                $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error.  Please try again later!!!</div>');
                redirect('signup/index');
            }
        }
    }
}
?>

This is how the signup form looks like,

codeigniter-signup-form

All fields are mandatory and once the user submits the form the input will be validated against a set of form validation rules. If the validation fails, user will be prompted to enter right data by showing the error message like this.

codeigniter-signup-form-validation-error

If validation succeeds, registration process will be completed and notified to the user.

Login.php

This is the controller file for user login process. It asks for user's email address and password and check if the provided login credentials are correct or not.

<?php
class login extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url','html'));
        $this->load->library(array('session', 'form_validation'));
        $this->load->database();
        $this->load->model('user_model');
    }
    
    function index()
    {
        // get form input
        $email = $this->input->post("email");
        $password = $this->input->post("password");

        // form validation
        $this->form_validation->set_rules("email", "Email-ID", "trim|required|xss_clean");
        $this->form_validation->set_rules("password", "Password", "trim|required|xss_clean");

        if ($this->form_validation->run() == FALSE)
        {
            // validation fail
            $this->load->view('login_view');
        }
        else
        {
            // check for user credentials
            $uresult = $this->user_model->get_user($email, $password);
            if (count($uresult) > 0)
            {
                // set session
                $sess_data = array('login' => TRUE, 'uname' => $uresult[0]->fname, 'uid' => $uresult[0]->id);
                $this->session->set_userdata($sess_data);
                redirect("profile/index");
            }
            else
            {
                $this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Wrong Email-ID or Password!</div>');
                redirect('login/index');
            }
        }
    }
}
?>

It produces a login form like this,

codeigniter-login-system-form

If login failed, the user will be shown an error message like this,

codeigniter-login-form-validation-error

If user credentials are valid, then it will be stored in session and user will be redirected to profile/dashboard page.

Profile.php

This is the controller for the User Profile page. It lists user profile summary and other details.

<?php
class profile extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('url','html'));
        $this->load->library('session');
        $this->load->database();
        $this->load->model('user_model');
    }

    function index()
    {
        $details = $this->user_model->get_user_by_id($this->session->userdata('uid'));
        $data['uname'] = $details[0]->fname . " " . $details[0]->lname;
        $data['uemail'] = $details[0]->email;
        $this->load->view('profile_view', $data);
    }
}
?>

That's it. These are all the important controller files required for the code igniter user registration and login system. Now run the app and go to Home page.

codeigniter-login-and-registration-tutorial-home-page
CodeIgniter Login and Registration System - Home Page

Click on Signup link and it will take you to the user signup form.

codeigniter-login-and-registration-tutorial-signup-page

Now enter the details and submit the form. If things gone right, you will be shown with a success message like this,

codeignitor-user-registration-process-success

Now click on the Login link to go to the login page.

codeigniter-login-and-registration-tutorial-login-page

Provide the email and password which you have registered earlier. Now you will be redirected to your Profile page.
codeigniter-login-and-registration-tutorial-profile-page
CodeIgniter Login and Registration Module - User Profile Page

To sign-out the session, click on Logout link at the top navigation menu which will take you back to Home page.

CodeIgniter Login and Registration Source Code:

Download Source

Don't Miss: CodeIgniter AJAX Modal Contact Form

Well! Now we have created user login and registration system in codeignator. I hope you have enjoyed this codeigniter login and registration tutorial. Please let me know your queries through comments :)

18 comments:

  1. thanks a lot for this tutorial

    ReplyDelete
  2. When I logged in, it shows "Wrong Email-ID or Password"

    help!

    ReplyDelete
  3. but sessions not destroyed here after logout.when i back after logout page is redirect to home page

    ReplyDelete
  4. http://127.0.0.1/ci%20login%20and%20registration/home/

    403 error show. pls help me. i don't understand which path gave in url

    ReplyDelete
  5. May I ask why the use of "ENGINE=MyISAM" and not "ENGINE=InnoDB"? I was under the impression that MyISAM is for version before mySQL 5.5.

    ReplyDelete
  6. Email-ID

    Unable to access an error message corresponding to your field name Email-ID.(xss_clean)
    Password

    Unable to access an error message corresponding to your field name Password.(xss_clean)

    ReplyDelete
  7. help sir

    Email-ID

    Unable to access an error message corresponding to your field name Email-ID.(xss_clean)
    Password

    Unable to access an error message corresponding to your field name Password.(xss_clean)

    ReplyDelete
    Replies
    1. load the helper('security') to fix your problem

      Delete
    2. load the helper('security') to fix your problem

      Delete
    3. Hi Rodel, here is the solution that worked for me. Just remove xss_clean from your validation.. reason being, xss_clean is no longer part of form validation in codeigniter 3

      Delete
  8. i place asset folder application inside but css and js not working, how can i do ?help me beacuse i am new in codeigniter
    Thank you

    ReplyDelete
  9. login and signup links doesnt work. I keep getting 404. I notice we you use multiple controller so I write the routes.php like this:

    $route['default_controller'] = 'home';
    $route['signup'] = 'signup';
    $route['login'] = 'login';
    $route['profile'] = 'profile';

    But it still not working. Can you tell me what should I do to fix this?

    ReplyDelete
  10. yeah me too i think new ci cant work well this source ?

    ReplyDelete
  11. how can i navigate the home page?

    ReplyDelete
  12. Please I'm having problem here, home page does not display as yours, can we communicate through eamil please? well my email is munirmdee@gmail.com

    ReplyDelete

Contact Form

Name

Email *

Message *