I am thinking of implementing a small tracking system that will track users logon / logoff times and also track who is currently logged on. It all makes sense to me except for the tracking of when a user logs off. Its easy enough when a user clicks a "log off" button which calls a function that can update the database with the logoff time but what if the user just exits out of the browser. How can I create a function that will handle this event and I guess any other situations I have not thought of when a user exits a php application an informal way. Also, any links to online tutorials on this subject would be much appreciated.
you can use Javascript to call PHP function (via AJAX) on window unload event or just log user out after e.g. 30 minutes of inactivity automatically.
You won't be able to track when the user closes the browser or your page.
What I have attempted to ask about tracking user closing page: http://stackoverflow.com/questions/1619946/ajax-when-user-leaves-page-good-or-bad-practice-implementation
Apparently it's not that good to send data on the before_unload
event.
Well what you can do is to consider users being logged off after inactivity for certain amount of time.
Each time when the users goes to a page, you store the timestamp. A user is said to be offline if the timestamp is more than 5 minutes old for example. You can store the timestamp into database or session.
Alternatively if you wish for it to be more accurate, you can call AJAX-ly every time interval (say 30 seconds) back to your server to prolong your activity timestamp.
The simplest solution is probably just to mark a user as "active" each time he does an action on your site (ie, each time a page is generated on the server) -- you already know how to do that.
And if a user has been marked as "active" a long time (ie, more than 5 minutes, for instance ; maybe more depending on the kind of content you have on your site) ago, you can consider he is not active anymore -- maybe not even on your site anymore, actually.
Of course, you have a couple of minutes of delay before detecting a user is not there anymore...
A possible complementary solution would be to use some kind of Ajax request done once every one or two minutes : this way, you have a shorter delay before detecting a user is not here anymore...
But, with this solution : you consider a user as active if he has a browser window/tab opened on your site -- even if he is not really using it (I always have lots of tabs opened in my firefox, some on websites I don't actually use for hours / days !)