Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Login/Logout If Session Timeout = true Do Something

I have a script that will login and logout a user. It works perfectly. Now I have like a widget that counts how many users are registered and activated as well as how many users are online. I do this by having a field in my users database that says online = 1 or 0. When the person logs in, online = 1 and logs out online = 0. Now I haven't taken into account that this field is only being updated because the user is doing something. I haven't taken into account that the session would timeout.

How can I make a function that says something like if session timeout = true then update users set online=0 where username=$username and user_id=$user_id.

like image 756
Harley Frank Avatar asked Jul 10 '26 01:07

Harley Frank


2 Answers

In your database table, add another column something like last_seen. Update this every time you see your users online. After a certain period of inactivity, they will be marked as inactive. In fact, I suggest you replace your online field with this.

For example,

ALTER TABLE users CHANGE COLUMN `online` `online` DATETIME; -- SAMPLE SQL query only

To check how many users are online:

SELECT * FROM users WHERE online>(NOW()-INTERVAL 1 HOUR); -- SELECTS all users online in the past hour.

If the user logs out, you can simply set the online = NOW()-INTERVAL 1 HOUR. Or, you can also retain your previous online field and you can check if the user is idle (using my suggestion) OR online=0.

like image 118
rationalboss Avatar answered Jul 15 '26 04:07

rationalboss


Instead of trying to use a boolean value to see if somebody is logged in, try using a TIMESTAMP. Then you can perform more accurate logic based on how long somebody has been away. If the last time somebody has loaded a page on your website was 30 minutes ago, do you think they're online? Do you even think they're at their keyboard?

like image 31
Andrew Avatar answered Jul 15 '26 04:07

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!