Reputation: 81
I want to create a page on which I can see, who is logged in on my site. For every user after logging in I create a session, and send a query to change the row "Logged" in mysql from No to Yes. Then, on the page I use PHP to show everyone, who has Yes set in mysql, and it works. But, I have a problem, which occurs when someone close the browser without clicking Logout - the query doesn't execute and the Yes value in mysql stays... What can I do to create a page like this?
Upvotes: 1
Views: 211
Reputation: 2743
Instead of having a boolean value for logged in or out, determine a reasonable amount of time for the session to expire (e.g., 1 month) and then add that amount of time to a timestamp and store that in the database as session_expires
or something. Then you can check if the user's session has expired whenever you do your login checks.
Additionally, to manually expire the session (for instance if a user logs out) just set the session_expires
field to a timestamp in the past.
EDIT
I didn't have access to a computer over the weekend, so I couldn't properly update my answer.
If you need to see active users, one thing I've done in the past is to use a last_seen
timestamp field that updates any time the user does anything on the site. Then, on your "users logged in" page, just query for something recent like "last seen in the past 15 minutes."
Upvotes: 2
Reputation: 439
The fact that the user keeps on staying logged in is due to the PHP SESSION TIMEOUT which may be configured in PHP settings php.ini.
Have a look at http://php.net/manual/en/function.session-set-save-handler.php to learn how to set a session shutdown handler (that will be called once the session becomes invalid). When the shutdown handler is called, set your current session's "logged" to false in the database. Still, it may take up to 24 minutes (default value in php.ini for session timeout - session.gc_maxlifetime = 1440
minutes).
Decrease this value (session.gc_maxlifetime
) to 2-3 minutes and have a ajax function on each of your pages keeping the session alive. This will definitely increase your server's load but you will definitely have a better representation of the currently active users. You can decrease the value from php.ini
or by usig ini_set(‘session.gc_maxlifetime’,30);
in your code.
Regards
Upvotes: 1
Reputation: 2914
You cannot do anything about that, but defining a timeout. That means your initial call after logging in that sets your customer row to "YES" should be triggered on every request (or to spare resources, every minute) to update a date column in that very customer row. If no update comes in anymore, you define that customer as "not logged in anymore" and update the column to "NO"
Upvotes: 1