Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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');
} 
like image 390
AyJane Bouvier Avatar asked May 30 '13 02:05

AyJane Bouvier


2 Answers

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

like image 156
M Khalid Junaid Avatar answered Sep 24 '22 12:09

M Khalid Junaid


you can store data in session object and user redirect any page , you can check session object already exist if not exist you can show alert, session is expired

like image 33
M.B Kakadiya Avatar answered Sep 23 '22 12:09

M.B Kakadiya