How to get user logout when he close browser


I have a website with login system after user and password are correct update user set flag 1 to not allow other people to connect with that user at same time

$sql="update user set flag = 1 where id_user =".$_SESSION['id_user'];

i have a logout.php who reset flag to 0 when i click logout button,but i also want to changed flag to 0 when user close browser.

I tried to sloved it with : javascript/jquery onbeforeunload unload and Sessions destory but i failed


You cannot do it this way.

Upon logon, you should check your session store whether there is a session for the user requesting logon. This of course needs a session store that you can actually check, ie. in a database.

I have a suggestion to solve with PHP, forgetting JavaScript

Stores the last request time from the logged user in your database, maybe in a field of the user table and in a cookie also (client side). So, every time the user make a request, update this field on the user table to the current time and the cookie also.

If anybody try to connect with a user that have flag = 1, verify the last request time. If it was five (or ten, or twenty, or whatever) minutes ago or more, allow log in. If it was less than this time, just not allow.

If allowed, then we have two person with a session in the system, so the two are logged, it is a problem.

To solve this, when anyone of them try to view the page, if the last request time stored in cookie (client side) is different from the stored in database, so destroy session. If is equal, the navigation is allowed and the last request time is update again (in the cookie and database).

The idea is that five (or ten, or twenty, or whatever) minutes of inactivity means that the user leaves.

You can also change session.gc_maxlifetime in php.ini to a lower time. For example, to five minutes, try:


After change php.ini, restart Apache.

See Default session time out in Apache and CentOS

This video can help you solving your question :)
By: admin