How to exec a function when codeigniter session ex

2019-08-19 03:39发布

问题:

I got an users table on my database with a "Online" field, it gets the value "1" when the user loggin, and changes to 0 when the user logout. The problem is that if the user close the tab and don't click on the "Logout" button he stays Online forever.

So I would like to hook some kind of function so when the session expires it changes the value of this "Online" field - on the database - to "0".

I'm open to suggestions of course, because I don't what is the right approach for this.

回答1:

Change the online field into datetime field,

Update the field using a central controller you're extending from, or use a hook to trigger the update of the field each time there's a request (You may put the code in the session validation function that you use to make sure a user is logged-in before triggering actions).

Then you can use the timediff SQL function to see if the user is active or not.



回答2:

You can do this by extending CI_Session

Create a php file inside application/core/MY_Session.php

class MY_Session extends CI_Session
{

public function __construct() {
    parent::__construct();
}

function sess_destroy() {

    //update the Online filed as required
    $this->CI->db->update('YOUR_TABLE', array('YOUR_DATA'), array('YOUR_CONDITION'));

    //call the parent 
    parent::sess_destroy();
}

}


回答3:

You have a specific problem. But I have one idea for this.

You can go on

system/libraries/Session.php

and update the function function sess_destroy() - line 398

In this function you can change the status on Database, and in this way you always will change the status when session destroy.

If you use unset_userdata(), than you need to change the function function unset_userdata($newdata = array() line 481 on the same file.