Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating MySQL database when user closes browser

Tags:

php

mysql

I'm developing a web application for a research company and one of the requirements is that a user can only log in on one device at a time.

So I developed a pretty basic system where when you log in some PHP updates a user's row in the database from 0 to 1 and when you click the logout button it updates that row again from 1 to 0.

The only problem is if the user does not use the logout button and simply closes the browser, it will end the session and log them out but their row in the databse will not be updated.

Is there a way to update the database on browser close?

like image 594
aadu Avatar asked Dec 15 '22 19:12

aadu


2 Answers

You can use unload event where you will send an ajax request to server which will update the flag in mysql. You can try following jquery syntax.

$(window).bind('unload', function(){
    $.ajax({
        type: 'get',
        async: false,
        url: 'path/to/file.php'
    });
});
like image 168
Dr. Dan Avatar answered Dec 18 '22 08:12

Dr. Dan


There is no reliable way. You can call a javascript function on page close, which in turn fires a request to your server, telling it that the session is done, but again: javascript may be turned off, and it may not even executed at all. Your best bet is to work with a time-out: store the time of the last action. If longer than 10 minutes ago, "expire" the session.

like image 32
Berry Langerak Avatar answered Dec 18 '22 09:12

Berry Langerak