Expire session automatically and detect if the session has expired in Codeigniter

AyJane Bouvier picture AyJane Bouvier · May 30, 2013 · Viewed 7.4k times · Source

I've seen plenty of questions here about my topic but it seems I still haven't found my answer. What I'm actually looking for is when the session expires the user will be automatically redirected to a page saying Your session has already expired. Please register to continue browsing..

Actually I have no idea on how I could determine if the user's session has already expired. Here's what I have so far.

Thanks.

function trial() {

    $this->db->select()->from('user')->where('user_type', 'tester');
    $tester = $this->db->get();

    foreach ($tester->result() as $row) {

        $data = array(
            'id' => $row->id,
            'first_name' => $row->first_name,
            'last_name' => $row->last_name,
            'display_name' => $row->display_name,
            'email' => $row->email,
            'avatar' => $row->avatar,
            'user_type' => $row->user_type,
            'logged_in' => TRUE
        );
        $this->session->set_userdata($data);
    }

    redirect(base_url(), 'refresh');
} 

Answer

M Khalid Junaid picture M Khalid Junaid · May 30, 2013

You can check user's session by making the ajax call and wrap it into the setInterval jquery's function like

setInterval(function() {
  // Do something every 1 minute 
$.ajax({
type : 'POST',
url  : '<?php echo site_url("CONTROLLERNAME/check_session")?>'
success : function(data){
if(data){
   //your session is not expired
}else{
   //your session is already expired
 window.location.href="your url"; // or you can redirect from here also
} 
});
}, 60000);


 //This function checks your session 
 function check_session(){
    $id = $this->session->userdata('id');
   if($id ){
         echo 1;
   }else{
         echo 0;
   redirect('your register controller');//redirect from here or you can redirect in the ajax response
   }

  die();
 }

Hope it makes sense