Click here to Skip to main content
15,868,340 members
Articles / Programming Languages / PHP
Technical Blog

Create user login with Codeigniter

Rate me:
Please Sign up or sign in to vote.
4.50/5 (13 votes)
15 Oct 2012CPOL3 min read 278.3K   17   22
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
<?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

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
<?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
<?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
<?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

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;?>            
            <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>

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
<?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
<?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
<?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
<?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)


Written By
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.

Comments and Discussions

 
QuestionManda error 404 al momento de dar click en Login Pin
Member 1396639629-Aug-18 8:37
Member 1396639629-Aug-18 8:37 
QuestionRE: Pin
Member 1396358627-Aug-18 11:48
Member 1396358627-Aug-18 11:48 
QuestionInvalid username and/or password. Pin
Member 120423507-Oct-15 22:21
Member 120423507-Oct-15 22:21 
AnswerRe: Invalid username and/or password. Pin
Member 128213036-Jul-18 21:29
Member 128213036-Jul-18 21:29 
QuestionInvalid username or password Pin
Member 1163390922-Apr-15 8:54
Member 1163390922-Apr-15 8:54 
GeneralMy vote of 3 Pin
Gektorian27-Dec-14 3:27
Gektorian27-Dec-14 3:27 
SuggestionSeparate functionality logic Pin
Gektorian27-Dec-14 3:25
Gektorian27-Dec-14 3:25 
Questionlogin/process not found Pin
Member 1061104819-Feb-14 20:38
Member 1061104819-Feb-14 20:38 
AnswerRe: login/process not found Pin
saudahmed17-Mar-14 18:55
saudahmed17-Mar-14 18:55 
GeneralRe: login/process not found Pin
satusrolas3-Jun-14 5:43
satusrolas3-Jun-14 5:43 
Questionblank page if autoload database Pin
okta_via26-Nov-13 23:04
okta_via26-Nov-13 23:04 
AnswerRe: blank page if autoload database Pin
saudahmed17-Mar-14 18:57
saudahmed17-Mar-14 18:57 
QuestionHow to show on dashboard session first name and last name Pin
Member 1035466423-Oct-13 1:50
Member 1035466423-Oct-13 1:50 
Question[ask] Pin
orpheus8710-Oct-13 1:55
orpheus8710-Oct-13 1:55 
AnswerRe: [ask] Pin
jotorres10-Oct-13 2:24
jotorres10-Oct-13 2:24 
QuestionThanks but possible error? Pin
RobertSF29-Aug-13 0:29
professionalRobertSF29-Aug-13 0:29 
GeneralMy vote of 5 Pin
WesMcGJr14-Feb-13 6:45
WesMcGJr14-Feb-13 6:45 
Questionlogin/process Pin
karjogedhe29-Jan-13 23:06
karjogedhe29-Jan-13 23:06 
GeneralMy vote of 5 Pin
NightCodeStalker14-Jan-13 17:55
NightCodeStalker14-Jan-13 17:55 
GeneralMy vote of 5 Pin
NightCodeStalker14-Jan-13 17:40
NightCodeStalker14-Jan-13 17:40 
GeneralRe: My vote of 5 Pin
jotorres29-Jan-13 3:50
jotorres29-Jan-13 3:50 

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

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