Photo of David Winter

david winter

Authentication with CodeIgniter

Here’s how I do some basic authentication for a controller in CodeIgniter. It basically consists of creating a new class that extends the default Controller class. You then sub-class this on any controller that requires authentication.

Create your authentication controller in system/application/libraries and call it MY_Controller.php. It’s important that you prefix the controller name with MY_, or whatever you have specified $config['subclass_prefix'] as in your configuration.

<?php

class MY_Controller extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        if (!$this->session->userdata('loggedin'))
        {
            header('Location: /sessions/login');
        }
    }
}

This basically checks if the session data for loggedin is set to true. If not, it’ll redirect the user to the /sessions/login URL. This means we have to create a basic controller to handle the sessions.

<?php

class Sessions extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
    }

    public function login()
    {
        $this->load->view('header');
        $this->load->view('sessions/login');
        $this->load->view('footer');
    }

    public function authenticate()
    {
        $this->load->model('user', '', true);
        if ($this->user->authenticate($this->input->post('username'), $this->input->post('password')))
        {
            $this->session->set_userdata('loggedin', true);
            header('Location: /');
        }
        else
        {
            header('Location: /sessions/login');
        }
    }

    public function logout()
    {
        $this->session->unset_userdata('loggedin');
        header('Location: /');
    }
}

The login view is a basic form with fields for username and password that submits to /sessions/authenticate. This controller then loads the user model and checks that a user with the username and password exists. If so, it sets the session data for loggedin to true and redirects the user back to the default controller. If not, it takes the user back to the login page.

Then to implement the authentication in a controller, simply do:

<?php

class SecretPlace extends MY_Controller
{
...

It’s a good idea to store your session data in your database and encrypt your cookies with $config['sess_encrypt_cookie'] = TRUE; in config.php. That way people won’t be able to snoop around and try to trick your application into thinking they’re authenticated.