Login & Logout Code in PHP Codeigniter

In this CodeIgniter Login & Logout System tutorial, we will show you how to create a login and logout system in CodeIgniter. You will learn how to authenticate users by their credentials.

Most websites require users to log in before they can perform certain actions. In other words, a login script is used to provide authentication for web pages.

We will guide you through the process of creating a login system in CodeIgniter so that your users can log in and access restricted parts of your website. Additionally, we will also show you how to create a logout system so that users can safely log out of your website.

Codeigniter Login

Contents

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Make New Controller
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Latest

In this next step, we’re going to download the newest version of Codeigniter. To do this, go to the website Download Codeigniter and get the most up-to-date setup. After you’ve downloaded it, unzip the setup in your local system’s xampp/htdocs/ folder. You can also rename your project folder to whatever you’d like.

Basic Configuration

Now it’s time to do some basic configuration settings on the config.php file. To do this, we’ll navigate to the application/config/config.php file and open it up in a text editor.

set base url like this:-

$config['base_url'] = 'http://localhost/projects/demo';

Create Database With Tables

For this next step, we’ll need to create a database with the name “demo” To do this, we’ll open up PHPMyAdmin and create the database with that name. Once it’s successfully created, we can use the following SQL query to create a table in the database.

CREATE TABLE IF NOT EXISTS users(
    id int(10) unsigned NOT NULL auto_increment,
    user_name varchar(150) collate latin1_general_ci NOT NULL,
    password varchar(100) collate latin1_general_ci NOT NULL,
    first_name varchar(45) collate latin1_general_ci NOT NULL,
    last_name varchar(45) collate latin1_general_ci NOT NULL,
    PRIMARY KEY  (id)
  );

Setup Database Credentials

In the following step, we’ll connect our CRUD app project to the database. To do this, we’ll go to the

application/config/database.php

file and set up our database credentials. In this file, we’ll add our database name, username, and password.

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'demo',
    '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
);

Create Controller

Now we need to create a controller name Auth.php. In this controller we will create some method/function. We will build some of the methods like :

  • Index() – This is used to showing a login form
  • post_login() – This function authenticates user credentials and starts moving forward
  • logout() – It is used to destroy the built-in session
  • dashboard – After successfully logging in, the user can redirect this method
<?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');
    }
}

Create Model

To create a login system in CodeIgniter, follow these simple steps:

  1. Go to your “application/models/” folder.
  2. Create a new file named “Form_model.php”.
  3. Open the “Form_model.php” file in a text editor.
  4. Inside the file, write the business logic for checking the user’s credentials from the database. Here is an example code:
<?php
class Form_model extends CI_Model {
  
    public function __construct()
    {
        $this->load->database();
    }
     
    public function auth_check($data)
    {
        $query = $this->db->get_where('users', $data);
        if($query){   
         return $query->row();
        }
        return false;
    }
     
}

Create Views

Now we need to create views for showing login form also showing dashbaord. So now create first view name login.php and put the below html in this file.

<html>
    <head>
        <link rel="stylesheet" href="css/style.css" />
        <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css" />
        <title>Sign in</title>
    </head>
    <style type="text/css">
        body {
        background-color: #F3EBF6;
        font-family: 'Ubuntu', sans-serif;
        }
        div.error {
        margin-bottom: 15px;
        margin-top: -6px;
        margin-left: 58px;
        color: red;
        }
        .main {
        background-color: #FFFFFF;
        width: 400px;
        height: 400px;
        margin: 7em auto;
        border-radius: 1.5em;
        box-shadow: 0px 11px 35px 2px rgba(0, 0, 0, 0.14);
        }
        .sign {
        padding-top: 40px;
        color: #8C55AA;
        font-family: 'Ubuntu', sans-serif;
        font-weight: bold;
        font-size: 23px;
        }
        .un {
        width: 76%;
        color: rgb(38, 50, 56);
        font-weight: 700;
        font-size: 14px;
        letter-spacing: 1px;
        background: rgba(136, 126, 126, 0.04);
        padding: 10px 20px;
        border: none;
        border-radius: 20px;
        outline: none;
        box-sizing: border-box;
        border: 2px solid rgba(0, 0, 0, 0.02);
        margin-bottom: 50px;
        margin-left: 46px;
        text-align: center;
        margin-bottom: 27px;
        font-family: 'Ubuntu', sans-serif;
        }
        form.form1 {
        padding-top: 40px;
        }
        .pass {
        width: 76%;
        color: rgb(38, 50, 56);
        font-weight: 700;
        font-size: 14px;
        letter-spacing: 1px;
        background: rgba(136, 126, 126, 0.04);
        padding: 10px 20px;
        border: none;
        border-radius: 20px;
        outline: none;
        box-sizing: border-box;
        border: 2px solid rgba(0, 0, 0, 0.02);
        margin-bottom: 50px;
        margin-left: 46px;
        text-align: center;
        margin-bottom: 27px;
        font-family: 'Ubuntu', sans-serif;
        }
        .un:focus, .pass:focus {
        border: 2px solid rgba(0, 0, 0, 0.18) !important;
        }
        .submit {
        cursor: pointer;
        border-radius: 5em;
        color: #fff;
        background: linear-gradient(to right, #9C27B0, #E040FB);
        border: 0;
        padding-left: 40px;
        padding-right: 40px;
        padding-bottom: 10px;
        padding-top: 10px;
        font-family: 'Ubuntu', sans-serif;
        margin-left: 35%;
        font-size: 13px;
        box-shadow: 0 0 20px 1px rgba(0, 0, 0, 0.04);
        }
        .forgot {
        text-shadow: 0px 0px 3px rgba(117, 117, 117, 0.12);
        color: #E1BEE7;
        padding-top: 15px;
        }
        button {
        text-shadow: 0px 0px 3px rgba(117, 117, 117, 0.12);
        color: #E1BEE7;
        text-decoration: none
        }
        @media (max-width: 600px) {
        .main {
        border-radius: 0px;
        }
    </style>
    <body>
        <div class="main">
            <p class="sign" align="center">Sign in</p>
            <form action="<?php echo base_url('auth/post_login') ?>" method="post" accept-charset="utf-8">
                <input class="un" type="text" align="center" name="email" placeholder="email" />
                <?php echo form_error('email'); ?>
                <input class="pass" type="password" align="center" name="password" placeholder="Password" />
                <?php echo form_error('password'); ?>
                <button type="submit" align="center" class="submit">Sign in</button>
            </form>
        </div>
    </body>
</html>

Now we need to create dashboard.php, After login user can redirect this page. So create dashboard.php and put the below html here.

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <div class="row">
                        <div class="col-md-12">
                            <h3>
                                Login Successful
                                <?=$this->session->userdata('first_name')?>
                                <?=$this->session->userdata('last_name')?>
                            </h3>
                            <a href="<?= base_url();?>auth/logout">Logout</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

Start Development Server

For start development server, Go to the browser and hit below the url.

http://localhost/projects/demo/auth

Conclusion

Well, well, well, in this CodeIgniter Login and Logout tutorial, we have created a fancy-schmancy login form with all the bells and whistles. We made sure to authenticate our users and, if successful, we redirect them to the dashboard page.

So, rest easy knowing that your users’ secrets are safe with us! If you have any questions or thoughts to share, don’t hesitate to use the comment form below to reach us. We’ll be waiting!

You May Also Like This :-

Integrate Razorpay with PHP Codeigniter

Codeigniter Autocomplete Search From Database – jQuery UI

One thought on “Login & Logout Code in PHP Codeigniter

  • Avatar for Terry Jossef
    March 1, 2023 at 11:50 am
    Permalink

    Hello, Torque Programming, i really love your tutorials, would you kindly do a tutorial on roles and permissions using codeigniter, thanks in advance.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *