This blog will explain you how to create session and use session in different files and I’ll also explain how to do login and logout using session in codeigniter.

What is session?

A Session basically refers to a time period for which use stays on our website. But technically its meaning is different. Session is an object which is used to store data in it and to retrieve from it. It would be accessed in entire website i.e in every pages. Session store its data on server. 

Syntax

$this->session->set_userdata('session_name', 'Value of session');

I’m assuming that you created database and table for tbluser(Columns: UserId,UserName,UserEmail,UserPassword,UserGender,UserHobbies,UserProfile). From this table I use UserEmail and UserPassword columns for login. Must enter some records in table so we can login through it.

General setup steps for session

1. You have to do changes in autoload.php file. It located application->config->autoload.php. Here set below code.

$autoload['libraries'] = array('session');

2. Then in controller you have to load session library in constructor.

$this->load->library('session');

Controller

Create a controller in application-> controllers folder. Write a code to login user and set session for it. I have mentioned comments please read it properly to understand the code.

crudController.php

<?php

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

    class crudController extends CI_Controller

    {

        function __construct()

        {

            parent::__construct();

            $this->load->helper('url'); /* load base url */

            $this->load->model('crudModel'); /* load model default which you create */

            $this->load->library('session'); /* load session library which we set in autoload.php file */

        }

        

        /* Set index page – Load you Login page here */

        public function index()

        {

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

        }

  

        /* Fuction for display logged in user’s data */

        public function DisplayLoginData()

        {

            /* Check session created or not */

            if (isset($this->session->userdata['user']))

            {

                $uemail  = $this->session->userdata['user'];

                $data["user_logindata"] = $this->crudModel->fetchuserlogindata($uemail);

                $this->load->view('displaylogindata', $data);

            }

            else

            {

                echo "<script>window.location='http://localhost/CRUDOperationCI/index.php/crudController/Login'</script>";

            }

        }

  

        /* Function for logout */

        public function Logout()

        {

            $this->load->view('logout');

        }

        

        /* Function for user login – called when user click on login button */

        public function UserLogin()

        {

            if ($this->input->post("btnlogin"))

            {

                $uemail = $this->input->post("txtuemail");

                $upass  = $this->input->post("txtpassword");

                

                $success = $this->crudModel->userlogin($uemail, $upass);

                

                if ($success)

                {

                    $this->session->set_userdata('user', $uemail); /*create session and store value of session*/

                    echo "<script>alert('Login successfully..!!');window.location='http://localhost/CRUDOperationCI/index.php/crudController/DisplayLoginData'</script>";

                }

                else

                {

                    echo "<script>alert('Error while login..!!');window.location='http://localhost/CRUDOperationCI/index.php/crudController/Login'</script>";

                }

            }

        }

    }

?>

Model

Create model in application->models folder. Write query for login and fetch data of logged in user. Below the code of model.

crudModel.php

<?php

    class crudModel extends CI_Model

    {

        /* Login query */

        public function userlogin($uemail, $upass)

        {

            $this->db->select('*');

            $this->db->from('tbluser');

            $this->db->where('UserEmail', $uemail);

            $this->db->where('UserPassword', $upass);

            $query = $this->db->get();

            return $query->row();

            

        }

        

        /* Fetch user login data using session email id */

        public function fetchuserlogindata($uemail)

        {

            $this->db->select('*');

            $this->db->from('tbluser');

            $this->db->where('UserEmail', $uemail);

            $query = $this->db->get();

            return $query->row();

            

        }

    }

?>

Views

Create login.php, displaylogindata.php and logout.php views application->views folder.

login.php

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Login</title>

    <style>

        input[type=text],input[type=email],input[type=password]{

            width:100% !important;

        }

        table{

            border: 1px solid #CACFD2;

        }

        form {

            margin: 10% auto 0;

        }

    </style>

</head>

<body>

    <form method="post" action="<?php echo base_url(); ?>index.php/crudController/UserLogin">

       <center><h1>Login Form CI</h1></center>

        <table align="center" border="0">

            <tr>

                <td>Email Address:</td>

                <td><input type="email" name="txtuemail"></td>

            </tr>

            <tr>

                <td>Password:</td>

                <td><input type="password" name="txtpassword"></td>

            </tr>

            

            <tr>

                <td colspan="2" align="center"><input type="submit" value="SignIn" name="btnlogin"></td>

            </tr>

        </table>

    </form>

</body>

</html>

Note: In this file in form tag you must have to set action property. In action property set path of the function which you want to call while this form processed. Functions are written into controller.

action="<?php echo base_url(); ?>index.php/crudController/UserLogin"

where crudController in my controller name and UserLogin is my function name for login.

After clicking on SignIn button if you enter valid email and password then move to the display page and if you enter invalid email or password then you will see one popup Invalid Email or Password..!! and stay at login page.

displaylogindata.php

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Display Data</title>

    <style>

        body{

            margin: 10% auto 0;

        }

        td{

            text-align: center;

        }

    </style>

</head>

<body>

    <center><h1>Display Login Data</h1></center>

    <table align="center" border="1">

        <tr>

            <td><h2>Welcome: <?php echo $user_logindata->UserName; ?></h2></td>

        </tr>

        <tr>

            <td><h3><a href="<?php echo base_url(); ?>index.php/crudController/Logout">Logout</a></h3></td>

        </tr>

    </table>

</body>

</html>

Note: In the top of the file I wrote one code that will execute when display file execute and it will check if there is not any session created then it redirect automatically to the login page. And also without login you can’t open display page.

Remove Session

If you want to logout then create one file logout.php. In that file destroy session using $this->session->unset_userdata('session_name'); then redirect page to the login page using header(“Location:file_name”) or window.location function.

logout.php

<?php

    $this->session->unset_userdata('user');

    echo "<script>alert('Logged out successfully..!!');window.location='http://localhost/CRUDOperationCI/index.php/crudController/Login'</script>";

?>