Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Create user login with Codeigniter

, 15 Oct 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
How to create user login with Codeigniter.

At some point you might need to create a user login for your project while using the Ccodeigniter framework. For those of you who are just getting started with this, you will see within this next post that it is very simple to create.

Let’s cut right to the chase:

Create login controller

The first thing that needs to be done is the login controller for your project. Within this login, we will create an index function that will load our login view. Remember, for good programming habits, we will also include our construct, and call the parent construct as well.

Filename: login.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Jorge Torres
 * Description: Login controller class
 */
class Login extends CI_Controller{
    
    function __construct(){
        parent::__construct();
    }

    public function index(){
        // Load our view to be displayed
        // to the user
        $this->load->view('login_view');
    }
}
?>

Once our logion controller is created, we can go ahead and create our login_view file. I will create a very simple form, without any style. That way, if needed, you can add the style that you like.

Filename: login_view.php

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 
  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>

<head>    
    <title>Jotorres Login Screen | Welcome </title>
</head>
<body>
    <div id='login_form'>
        <form action='<?php echo base_url();?>login/process' method='post' name='process'>
            <h2>User Login</h2>
            <br />            
            <label for='username'>Username</label>
            <input type='text' name='username' id='username' size='25' /><br />
        
            <label for='password'>Password</label>
            <input type='password' name='password' id='password' size='25' /><br />                            
        
            <input type='Submit' value='Login' />            
        </form>
    </div>
</body>
</html>

If you notice above, the form action is set to – base_url()login/process. This is assuming that your base_url is set as the following: “http://yourdomain.com/”. Notice the final slash. So now we need to create a method in our controller called process. Within this method, we will call our model, and process our logic in the model. Let’s do so:

<?php 
    public function process(){
        // Load the model
        $this->load->model('login_model');
        // Validate the user can login
        $result = $this->login_model->validate();
        // Now we verify the result
        if(! $result){
            // If user did not validate, then show them login page again
            $this->index();
        }else{
            // If user did validate, 
            // Send them to members area
            redirect('home');
        }        
    }
?>

Now that we have that method, we can create our login_model file. This file will have a method called validate. In this method we will query our database, looking for a user, and will return true or false, depending on the outcome. Also, we will use the codeigniter sessions class, to create a user-specific session. Let’s take a look at how its done.

Filename: login_model.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Jorge Torres
 * Description: Login model class
 */
class Login_model extends CI_Model{
    function __construct(){
        parent::__construct();
    }
    
    public function validate(){
        // grab user input
        $username = $this->security->xss_clean($this->input->post('username'));
        $password = $this->security->xss_clean($this->input->post('password'));
        
        // Prep the query
        $this->db->where('username', $username);
        $this->db->where('password', $password);
        
        // Run the query
        $query = $this->db->get('users');
        // Let's check if there are any results
        if($query->num_rows == 1)
        {
            // If there is a user, then create session data
            $row = $query->row();
            $data = array(
                    'userid' => $row->userid,
                    'fname' => $row->fname,
                    'lname' => $row->lname,
                    'username' => $row->username,
                    'validated' => true
                    );
            $this->session->set_userdata($data);
            return true;
        }
        // If the previous process did not validate
        // then return false.
        return false;
    }
}
?>

We are almost finished with this login script. If we have that the validation was unsuccessful, then we need to notify the user that something is wrong. Let’s add in a message indicating something went wrong. We will add a parameter to our index function in login controller. The default message will be null, meaning there will be nothing to display, but if an error occurs, we call the method with a message. Let’s see how we go about this matter:

Filename: login.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Jorge Torres
 * Description: Login controller class
 */
class Login extends CI_Controller{
    
    function __construct(){
        parent::__construct();
    }
    
    public function index($msg = NULL){
        // Load our view to be displayed
        // to the user
        $data['msg'] = $msg;
        $this->load->view('login_view', $data);
    }
    
    public function process(){
        // Load the model
        $this->load->model('login_model');
        // Validate the user can login
        $result = $this->login_model->validate();
        // Now we verify the result
        if(! $result){
            // If user did not validate, then show them login page again
            $msg = '<font color=red>Invalid username and/or password.</font><br />';
            $this->index($msg);
        }else{
            // If user did validate, 
            // Send them to members area
            redirect('home');
        }        
    }
}
?>

Now let’s display that message in our login_view:

Filename: login_view.php

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 
    'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>

<head>    
    <title>Jotorres Login Screen | Welcome </title>
</head>
<body>
    <div id='login_form'>
        <form action='<?php echo base_url();?>login/process' method='post' name='process'>
            <h2>User Login</h2>
            <br />
            <?php if(! is_null($msg)) echo $msg;?>

Lastly, we need to create the members only page and controller. This controller will verify if the user is logged in, and if not, then redirect to the login page. We will create the validation within the construct, since each time the user access this ‘home’ page, this construct will run. If we were to only write it in the index function, then only the index would get validated, and not all other functions.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Jorge Torres
 * Description: Home controller class
 * This is only viewable to those members that are logged in
 */
 class Home extends CI_Controller{
    function __construct(){
        parent::__construct();
        $this->check_isvalidated();
    }
    
    public function index(){
        // If the user is validated, then this function will run
        echo 'Congratulations, you are logged in.';
    }
    
    private function check_isvalidated(){
        if(! $this->session->userdata('validated')){
            redirect('login');
        }
    }
 }
 ?>

Add Logout

For everything that get’s logged in, there should be a way to log out. It very simple, and we will add this logic to our home controller. Also, we will add a link in the members area to logout.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Jorge Torres
 * Description: Home controller class
 * This is only viewable to those members that are logged in
 */
 class Home extends CI_Controller{
    function __construct(){
        parent::__construct();
        $this->check_isvalidated();
    }
    
    public function index(){
        // If the user is validated, then this function will run
        echo 'Congratulations, you are logged in.';
        // Add a link to logout
        echo '<br /><a href=''.base_url().'home/do_logout'>Logout Fool!</a>';
    }
    
    private function check_isvalidated(){
        if(! $this->session->userdata('validated')){
            redirect('login');
        }
    }
    
    public function do_logout(){
        $this->session->sess_destroy();
        redirect('login');
    }
 }
 ?>

There you have it folks, a simple logic for logging in and out a user from a website. This can obviously be enhanced to your likings as I have made this post very broad to show how quickly this can be done.

Recommendations

Something to remember is to load your session library in the autoload file. Also, you need to set an encryption key, even if you are not planning on using it, codeigniter requires you to create one.

Load the sessions library like this:

Filename: autoload.php – Can be found at: path/to/ci/folder/application/config/autoload.php

<?php 
 
/*
| -------------------------------------------------------------------
|  Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
|    $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/

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

?>

To set up the encryption key, go to the file config.php

Filename: config.php – Can be found at: path/to/ci/folder/application/config/config.php

<?php 
$config['encryption_key'] = 'Type in your key';
?>

With this configured, you are ready to execute the script.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

jotorres
Software Developer
Puerto Rico Puerto Rico
As a computer scientist, I strive to learn more everyday in my field. Everything I learn, I share with my community by writing articles for future references.
Follow on   Twitter

Comments and Discussions

 
Questionlogin/process not found PinmemberMember 1061104819-Feb-14 21:38 
AnswerRe: login/process not found Pinmembersaudahmed17-Mar-14 19:55 
GeneralRe: login/process not found Pinmembersatusrolas3-Jun-14 6:43 
Questionblank page if autoload database PinmemberMember 1042913027-Nov-13 0:04 
AnswerRe: blank page if autoload database Pinmembersaudahmed17-Mar-14 19:57 
QuestionHow to show on dashboard session first name and last name PinmemberMember 1035466423-Oct-13 2:50 
Question[ask] Pinmemberorpheus8710-Oct-13 2:55 
AnswerRe: [ask] Pinmemberjotorres10-Oct-13 3:24 
QuestionThanks but possible error? PinmemberMember 794339829-Aug-13 1:29 
GeneralMy vote of 5 PinmemberWesMcGJr14-Feb-13 7:45 
Questionlogin/process Pinmemberkarjogedhe30-Jan-13 0:06 
GeneralMy vote of 5 PinmemberNightCodeStalker14-Jan-13 18:55 
GeneralMy vote of 5 PinmemberNightCodeStalker14-Jan-13 18:40 
GeneralRe: My vote of 5 Pinmemberjotorres29-Jan-13 4:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141216.1 | Last Updated 15 Oct 2012
Article Copyright 2012 by jotorres
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid