User Login and Logout with the session

Now we are going to do the Login and Logout session part for this Project.

Login Page:




We will go one by one in each file and update some Code-Igniter files.
So I am considering my Project directory name is "CRUD Project".

Open file : CRUDProject\application\config\autoload.php

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

Open file : CRUDProject\application\config\config.php

- configure base url of the project
$config['base_url'] = 'http://localhost:8089/CRUDProject/';

Open file : CRUDProject\application\config\database.php

- Here you need to provide your database related credentials.
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'crudsession',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

Now you need to create files inside controllers, models, and views directory as below.

CRUDProject\application\controllers\Users.php
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 
 
class Users extends CI_Controller { 
     
    function __construct() { 
        parent::__construct(); 
         
        // Load form validation ibrary & user model 
        $this->load->library('form_validation'); 
        $this->load->model('user'); 
         
        // User login status 
        $this->isUserLoggedIn = $this->session->userdata('isUserLoggedIn'); 
    } 
     
    public function index(){ 
        if($this->isUserLoggedIn){ 
            redirect('users/account'); 
        }else{ 
            redirect('users/login'); 
        } 
    } 
 
    public function account(){ 
        $data = array(); 
        if($this->isUserLoggedIn){ 
            $userId = $this->session->userdata('userId');
            $loggedInUser = $this->user->getUserById($userId);

            $data['loggedInUser'] =  $loggedInUser;
            log_message("error", "Logged in User in Product ".$loggedInUser['first_name']);
             
            $this->load->view('users/account', $data); 
           
        }else{ 
            redirect('users/login'); 
        } 
    } 
 
    public function login(){ 
        $data = array(); 
      
        if($this->isUserLoggedIn){ 
          redirect('users/account');  
        }else{

        if($this->session->userdata('success_msg')){ 
            $data['success_msg'] = $this->session->userdata('success_msg'); 
            $this->session->unset_userdata('success_msg'); 
        } 
        if($this->session->userdata('error_msg')){ 
            $data['error_msg'] = $this->session->userdata('error_msg'); 
            $this->session->unset_userdata('error_msg'); 
        } 
         
        if($this->input->post('loginSubmit')){ 
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email'); 
            $this->form_validation->set_rules('password', 'password', 'required'); 
             
            if($this->form_validation->run() == true){ 
                
                $formArray = array();
                $formArray['email'] = $this->input->post('email');  
                $formArray['password'] = $this->input->post('password');
                $formArray['status'] = $this->input->post('status');

                $checkLogin = $this->user->validateLoginUser($formArray); 

                if($checkLogin){ 
                    $this->session->set_userdata('isUserLoggedIn', TRUE); 
                    $this->session->set_userdata('userId', $checkLogin['id']); 
                    redirect('users/account/'); 
                }else{ 
                    $data['error_msg'] = 'Wrong email or password, please try again.'; 
                } 
            }else{ 
                $data['error_msg'] = 'Please fill all the mandatory fields.'; 
            } 
        }          
        $this->load->view('users/login', $data); 
    }
    }
    public function logout(){ 
        $this->session->unset_userdata('isUserLoggedIn'); 
        $this->session->unset_userdata('userId'); 
        $this->session->sess_destroy(); 
        redirect('users/login/'); 
    }
}

CRUDProject\application\models\User.php
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 
 
class User extends CI_Model{ 
    function __construct() { 
        // Set table name 
        $this->table = 'users'; 
    }
    function validateLoginUser($formArray) {
        $this->db->where('email',$formArray['email']);
        $this->db->where('password',md5($formArray['password']));
        $this->db->where('status',1);
        return $user = $this->db->get('users')->row_array(); 
    }
    function getUserById($userId){
        $this->db->where('id',$userId);
        return $user = $this->db->get('users')->row_array();
    }
}

CRUDProject\application\views\users\account.php
<?php include('header.php')?>
 <div class="navbar navbar-dark bg-primary">
  <div class="container">
   <h3 class="navbar-brand">Welcome <?php echo $loggedInUser['first_name'].' '.$loggedInUser['last_name']; ?> !</h3>
   <h3 class="navbar-brand">Login Email: <?php echo $loggedInUser['email']; ?></h3>
      <a class="navbar-brand" href="<?php echo base_url('index.php/users/logout'); ?>" class="logout">Logout</a>
  </div>
 </div>

<div class="container" style="padding-top: 20px;">
<h1>
 CRUD Application in Code-Igniter
</h1>
</div>
  <?php include('footer.php')?>

CRUDProject\application\views\users\footer.php
<script src="<?php echo base_url().'assets/js/jquery-3.3.1.slim.min.js';?>"></script>
<script src="<?php echo base_url().'assets/js/bootstrap.min.js';?>"></script>
</body>
</html>

CRUDProject\application\views\users\header.php
<!DOCTYPE html>
<html lang="en">  
<head>
<title>CRUD Application in CodeIgniter</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/bootstrap.min.css';?>">
<style type="text/css">
body {
    font-family: "Lato", sans-serif;
}
.main-head{
    height: 150px;
    background: #FFF;   
}
.sidenav {
    height: 100%;
    background-color: #0275d8;
    overflow-x: hidden;
    padding-top: 20px;
}
.main {
    padding: 0px 10px;
}
@media screen and (max-height: 450px) {
    .sidenav {padding-top: 15px;}
}
@media screen and (max-width: 450px) {
    .login-form{
        margin-top: 10%;
    }
    .register-form{
        margin-top: 10%;
    }
}
@media screen and (min-width: 768px){
    .main{
        margin-left: 40%; 
    }
    .sidenav{
        width: 40%;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
    }
    .login-form{
        margin-top: 50%;
    }

    .register-form{
        margin-top: 20%;
    }
}
.login-main-text{
    margin-top: 20%;
    padding: 60px;
    color: #fff;
}
.login-main-text h2{
    font-weight: 300;
}
.btn-black{
    background-color: #000 !important;
    color: #fff;
} 
</style>
</head>
<body>

CRUDProject\application\views\users\login.php
<?php include('header.php')?>
<div class="sidenav">
         <div class="login-main-text">
            <h2><b>Application<br> Login Page</b></h2>
            <p>Login or register from here to access.</p>
         </div>
      </div>
      <div class="main">
         <div class="col-md-6 col-sm-12">
    <div class="login-form">
                             <!-- Status message -->
    <?php  
        if(!empty($success_msg)){ 
            echo '<div class="alert alert-dismissible alert-success">
                  <button type="button" class="close" data-dismiss="alert">&times;</button>
                  <strong>'.$success_msg.'</strong></div>'; 
        }elseif(!empty($error_msg)){ 
            echo '<div class="alert alert-dismissible alert-danger">
                  <button type="button" class="close" data-dismiss="alert">&times;</button>
                  <strong>'.$error_msg.'</strong></div>';
        } 
    ?>
    
    <!-- Login form -->
  
        <form action="" method="post">
            <div class="form-group">
                <label>User Email</label>
                <input type="email" name="email" class="form-control" placeholder="EMAIL" required="">
                <?php echo form_error('email','<p class="help-block">','</p>'); ?>
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" placeholder="PASSWORD" required="">
                <?php echo form_error('password','<p class="help-block">','</p>'); ?>
            </div>
                <input type="submit" name="loginSubmit" class="btn btn-primary" value="Login">
        </form>
        <br/>
        <p>Don't have an account? <a href="<?php echo base_url('index.php/users/registration'); ?>">Register</a></p>
    </div>
         </div>
  </div>
  <?php include('footer.php')?>

So if you have seen we have added bootstrap related files in the assets directory.
You can download the below files from their official sites.
- bootstrap.min.css
- jquery-3.3.1.slim.min.js
- bootstrap.min.js 

After this, you can run your application from Xampp Server directly.

Open the browser and Go to below link:
http://localhost:8089/CRUDProject/index.php/users/login

If you are getting Login Page then you are on the right path, if not then please let me know.
Test username: arvind@gmail.com and password: system123

Youtube video link for your reference.


Comments

Popular posts from this blog

How to read XLS and XLSX Excel files in Java

How to Read CSV File in Java