DEV Community

loading...

Login And Logout Code In Codeigniter With Example

robertlook profile image Robert Look ・1 min read

We would you how to create a login and logout system in Codeigniter. You will learn in this tutorial how to Codeigniter login code and logout into Codeigniter

Every website wants to login to our users for some activity. Without login, users can not do something on any website, because they want to login to our users on the website.

Login And Logout Code In Codeigniter With Example

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends CI_Controller {

     public function __construct()
        {
         parent::__construct();
         $this->load->model('Form_model');
             $this->load->library(array('form_validation','session'));
                 $this->load->helper(array('url','html','form'));
                 $this->user_id = $this->session->userdata('user_id');
        }


    public function index()
    {
     $this->load->view('login');
    }
    public function post_login()
        {

        $this->form_validation->set_rules('email', 'Email', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required');

        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        $this->form_validation->set_message('required', 'Enter %s');

        if ($this->form_validation->run() === FALSE)
        {  
            $this->load->view('login');
        }
        else
        {   
            $data = array(
               'email' => $this->input->post('email'),
               'password' => md5($this->input->post('password')),

             );

            $check = $this->Form_model->auth_check($data);

            if($check != false){

                 $user = array(
                 'user_id' => $check->id,
                 'email' => $check->email,
                 'first_name' => $check->first_name,
                 'last_name' => $check->last_name
                );

            $this->session->set_userdata($user);

             redirect( base_url('dashboard') ); 
            }

           $this->load->view('login');
        }

    }
    public function logout(){
    $this->session->sess_destroy();
    redirect(base_url('auth'));
   }    
   public function dashboard(){
       if(empty($this->user_id)){
        redirect(base_url('auth'));
      }
       $this->load->view('dashboard');
    }
}
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide