Login, logout and duration time in php and mysql?

与世无争的帅哥 提交于 2019-12-02 10:27:42

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!