Expire session automatically and detect if the session has expired in Codeigniter
Asked Answered
F

5

6

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');
} 
Frustum answered 30/5, 2013 at 2:27 Comment(0)
F
1

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

Firstly answered 30/5, 2013 at 6:53 Comment(0)
V
6

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

Vendible answered 30/5, 2013 at 6:22 Comment(10)
this is a god technique, but what if the user have JavaScript turned off? I need a solution that works without javascriptThulium
I know this topic is already old but, will benefit the others like me, I use the answer above with small modification. If you don't want to use js you can use meta data like this, <meta http-equiv="refresh" content="900;url=<?php echo base_url("logout"); ?>" />, which I saw in other website. Place this inside the <head></head> tag. The content="900; is the time which in seconds followed by url=<?php echo base_url("logout");?> which contains the logout method, in my case, separate controller. Hope this will help others in the future, but the .ajax above is the one for me. thanksHomosporous
@Homosporous content="900;url=<?php echo base_url("logout"); ?>, did the 900 number is in miliseconds or second ?Rheingold
how can i make an alert in login screen like "Your login session has expired due inactivity" ?Rheingold
I mean i add the text above the login form @MKhalidJunaidRheingold
@Rheingold it's in seconds, 900 is 15minutes. Regarding your question about login expiry notification, you can add in the url like localhost/logout=1 where 1 is the notification message that the session has expired due to inactivity.Of course you should have PHP code to validate that. I hope that help :)Homosporous
@Homosporous why they use else in else{ echo 0; redirect('your register controller');//redirect from here or you can redirect in the ajax response } if the result is 0 where would it be redirect ? i mean i still on the page right, so what does else stand for ?Rheingold
@Gagantous, That IF ELSE statement test if the $id has data or true, else $id is 0 or false, if $id = 0 or false it means that the session has expired, thus no data on it since it is already expired. So, the ELSE will redirect you to the login page since session already expired. You can add a condition in the login page that will display the notice like, localhost/login?expired=1. you can $_GET['expired'] = 1, display Session Expired, Login again. or you can do jquery to display the notice then redirect to login page once the OK button has been clicked.Homosporous
@Rheingold In the answer above, The setInterval(...) will check the function check_session() for every 1 minute. You can place the setInterval(...) in your footer, the function check_session can be place in another view, then you can load that view in a controller that you want like url : '<?php echo site_url("CONTROLLERNAME/check_session")?>'Homosporous
@Rheingold This is my footer.php - View function checkLogin() { $.ajax({ type : 'POST', url : js_base_url('checkLogin'), success : function(data){ if(data = 0){ if(!alert("Your session has timeout. You will be logout automatically. Login again to continue. Thank you!")){ var l = "<?php echo base_url('login/authentication?logout=1'); ?>"; window.location.href=l; }}}}); } This my CheckLogin.php - Controller function index(){ $usr = $this->session->userdata('s_data'); if($usr){ echo $data = '1'; }else{ echo $data = '0'; }}} I hope that helps you.Homosporous
K
1

Although not 100% reliable, you could set a cookie on the users machine. I would recommend setting the expiry about an hour in advance.

With every page that you wanted to know if the session had expired, you could check to see if both the cookie and the session existed. If it does...continue. If only the cookie remains, then you know that the session has expired and you need to redirect them to the page that you referred to in your question. If neither are present, then there is a problem and the user needs to restart everything.

Of course, for every page that a session is instantiated, the session expiry will restart, so you will need to reset the cookie. It could be a bit tedious, but it is what I would recommend.

Kozhikode answered 30/5, 2013 at 2:35 Comment(1)
Is there anyway for me to do it in the controller?Frustum
F
1

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

Firstly answered 30/5, 2013 at 6:53 Comment(0)
C
0

When you are starting the session, store the current time in a session variable. You can use a session_expire_checker function which will check current time and stored time to determine whether the session has expired. You should call the function from the constructor so that every function call will use this function automatically. In that function if session is expired, you redirect to another controller.

You have to use separate controller for the redirected URL, otherwise there would be infinite redirect.

Chopstick answered 30/5, 2013 at 6:37 Comment(0)
S
0

Codeigniter does not "fire an event" when the session expires. So either you write some code in each controller function to check if the user is still logged in. Or you use some small js in the footer (which I personally prefere):

<script>
    var mins = 15 * 60;
    var active = setTimeout("logout()",(mins*1000));
    function logout()
    {
        location='/account/timeout'; // <-- put your controller function here to destroy the session object and redirect the user to the login page.
    }
</script>
Santonin answered 29/8, 2016 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.