Codeigniter redirect to login page if session already expires

11,357

First, create a core Controller under application/core. You can call it MY_Controller.php

Here is an example for MY_Controller.php:

class User_Controller extends CI_Controller {

    public function __construct()
    {

        parent::__construct();

        if ($this->session->userdata['logged'] == TRUE)
        {
            //do something
        }
        else
        {
            redirect('login'); //if session is not there, redirect to login page
        }   

    }
}

Create your Controller Classes like below:

class Someclass extends User_Controller

Also you should pass a value which called "logged" in your session array. E.g:

$session = array('id' => $id, 'logged' => TRUE);
$this->session->set_userdata($session);

Now, if session ends, system will redirect user to login page. If you want to make this session control thing via JavaScript, you should write some code for it. By the way, I'm not suggesting this. You don't need to increase your system's workload. With my code, if a session ends when user want to visit another page, system will kick him out.

public function check_session()
{


    if(!$this->session->userdata['logged'])
    {
        redirect('someurl');
    }
}
Share:
11,357
SilverRay
Author by

SilverRay

Updated on June 05, 2022

Comments

  • SilverRay
    SilverRay almost 2 years

    I am new to codeigniter framework and I don't really get how does the built-in session works. What I want is that when the session expires the user will be redirected to login page. I checked the answers in google and other stackoverflow questions and tried every code in their but it does not work. In the native php session I only need to specify that if the session expires in the given time then redirect but when I applied it in codeigniter it does not work. I don't know also how to retrieve the session expiration value in config to compare it to the current time accumulated by the user during his/her logged session. Please help....

    This is in function in controller

    public function check_session()
    {
        $logged_in = $this->session->userdata('logged_in');
    
        if(!$logged_in)
        {
            $this->logout();
        }
    }
    

    And this is the ajax:

    setInterval(function(){
    $.ajax({
        type: 'POST',
        url: "<?php echo site_url('tms/check_session');?>",
        success: function(data){
            console.log(data);
        }
    });
    },300);
    
  • SilverRay
    SilverRay almost 8 years
    I tried your code but not inside my controller but inside my view header page and it works... Thanks...