From the description you gave, I imagine you do not save session, much less cookie, and leaving the site should log in again. So I present a simple example of 2 tables.
USERS
ID | NOME | SENHA | EMAIL...
1 | Papa Charlie | ***** | [email protected]
USER-LOGIN
ID | ID_USER | LOGIN_TIME | LAST_LOGIN
1 | 1 | 07/09/2014 11:00 | 07/09/2014 12:00 // login ontem
2 | 1 | 08/09/2014 13:00 | 08/09/2014 17:00 // login hoje
1) When the user logs in to the site, record in your DB USER-LOGIN the last updated time. Each login enters a record in USER-LOGIN
, and every request is updated.
In the example of the tables above, yesterday’s login lasted 1 hour (11 to 12) and today’s login lasted 4 hours (13 to 17)
2) The next step would be to send a request via js to update the field.
setTimeout(function(){
$.get("check_user.php");
} 60000 );
Every minute the page check_user.php
will receive user data and update the field LAST_LOGIN
What do you want to do with this information? Put it in the database or wouldn’t you need it? At simplest case you could pick up the timestamp at the time the user authenticates, the timestamp at the time of logout and check the total time logged in. The close tab/browser event can also catch you, but note that this does not cause the user to be "dropped" unless you are forcing this into your code. For loss of connection you could make a Polling through an ajax function...
– Adriano Leal
... and when that function does not get more result you consider that there was logout. But see that this way the code would be on the client side and depending on how your system is, would not have connection to the database and everything. I think the best thing would be to try to explain the final idea with this, so that someone can help in the best way.
– Adriano Leal
@Adrianoleal, my question is how will I store in the bank the moment of logout? If he clicks on the logout option, great but what if he just closes the tab, or browser...
– Diego Zanardo
@Adrianoleal, I believe Pope Charlie’s answer!
– Diego Zanardo
Yes, I also found Papa Charlie’s answer very good, @Diegozanardo. It does not cover everything you want, for example, in loss of connection requests would not work and you would lose that control, but if we take into account that connection losses will occur a few times there would be no problem. Ah, I also find it costly to spend every user session communicating with the bank every minute, but it’s an alternative, so it varies from case to case.
– Adriano Leal
Another thing, updating the information only when loading the page may not be ideal, if your pages have large contents (I do not know the content of your system) the user could stay on the page for a long time, for example reading a text or watching a video and you only recorded the date and time of when the user entered the page. The perfect scenario would be to make these requests in the tab/browser onClose event as well, but I’ve never done this in JS.
– Adriano Leal