views:

638

answers:

3

I would like to store the login, logout and duration time in database.

  • The login time is created when the user is authenticated(successfully logged in)
  • The logout time is created when the user clicks the logout button
  • The duration is logout - login time. (logout minus login)

But the problem is, what if the user didnt click the logout button. Here are the situations:

  • Internet loss
  • Close the browser/tab. (I need this must use javascript, but i donnu how to do it, any idea?)

EDIT:

I forgot to add something to the question, the program is a full flash program, there is no navigation to other page. Only 1 page

A: 

Regarding the closing of browser/tab, you can bind the unload event (window.onunload, jQuery's $(window).unload(fn), or any other) to notify your server. A more general purpose solution would be to periodically ping your server (say, every 5 min), but it might be annoying to the user, so do so judiciously.

K Prime
A: 

You can't rely on receiving an event for the user logging out, if they simply close their browser, or disappear from the internet.

In this case you'll have to have a session timeout of some kind, and record the logout when your app realises their session is too old.

If this is a real requirement, then I'd say you need a "cron" job monitoring the sessions for timeout. When a session has timed out, if the were logged on, it then records a "logout" event for that user.

Note that you can't use (for example) ASPNET's Session_End event, because that won't be reliably called either (for example if the server process restarts).

Another option is to add the logout time next time that user logs on - when they log on, you check for old sessions and assume that any which weren't closed lasted for a fixed amount of time since the last page hit.

That's really all you can do.

MarkR
A: 

It's important to remember that all session/log-in functions in PHP are usually cookie based. So, changing the lifetime of the session cookie should solve your problem:

http://us3.php.net/manual/en/function.session-set-cookie-params.php

Also, you can set the PHP sessions so they only use cookies:

http://us2.php.net/manual/en/session.configuration.php#ini.session.use-only-cookies

Again, you can catch the browser window / tab close but ... why? For instance I may have your site open in multiple tabs. If I close one of those tabs should I automatically be logged out of your website? That's a very bad design. Instead, set the session lifetime so it expires if the browser is closed and not just a tab. (Note also that window.unload will logout when any window on your site that closes - including a pop-up or an iframe. Do you really want that?)

http://us2.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime

If you want to store session state in a database try any one of these guides. Or, roll your own with session_set_save_handler

pygorex1