After the user successfully logs in, I store login = true in database. But how do I check if the user logged out by closing the browser without clicking the logout button? A
2017 edit: These days, your best bet is using websockets to track presence on a page/site.
You cannot detect when a user closes their browser or navigates off your site with PHP, and the JavaScript techniques of doing so are so far from guaranteed as to be useless.
Instead, your best bet is most likely to store each user's last activity time.
If you are trying to track the users that are 'online' then you might consider using a session for the individual user and instead of storing login=true in the db to display their status to you or others, store the last activity time for the user. When you pull up your list of online users, create your sql query to only return users with 'last_activity' within the last 10 minutes.
It might be better to store login=true in a session variable to check wheter or not the user is logged in. This would solve most of your problems ;)
You can do this with a combination of ways, 2 at the most i guess, with the one bothering on last activity, you combine it with using jQuery to check for inactivity, that is no mouse or keyboard events for some time, say about 10 to 20 mins, then once the idle time is confirmed, you make an ajax call to a php file that will update your database table showing user offline.
You can start with:
<script type="text/javascript">
idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 19) { // 20 minutes
$.ajax({
url: 'update_user.php',
type: 'POST',
datatype: 'json',
data: someData
});
}
}
</script>
Normally you would put such information in sessions.
$_SESSION['user'] = "A user name";
Then when you want to logout you do:
session_destroy();
Some more info on sessions here and a tutorial.
Why dont you use session or cookies for this instead of inserting it in the database. You can set the cookies by using setcookie() function or either you can make a session vaiable and store the value in it.