Check if user closed browser

Asked

Viewed 2,851 times

5

Would there be a way for me to know when a user closes the browser and, before closing, record in the bank that their session is inactive? Or, how can I make some external program that monitors if the person is with the browser open, and when it does not get an answer, consider that closed the browser?

I have an application that allows a maximum of three users logged in with the same account. At the moment the user logs in, I store in the database his user id and the time and date he logged in, as well as an 'active' flag indicating that he is logged in. If the person tries a fourth login, I check by the bank that there are already three authentications for that user and clay the fourth.

If it logs out, save this information in the database and allow it to log in once more, up to the limit of three logins. I know when the user logout, but I don’t know when he closes the browser.

  • 1

    Imagine that I am accessing your site when it lacks light: obviously it is impossible to detect that I "closed" the browser. Your goal is to promote user security (e.g. if you have a lot of people accessing the same account at the same time you have something weird going on), or your goal is to promote the security of your service (e.g. not letting 30 people share the same Netflix/Spotify/etc account.)?

  • by javascript there is onclose method that checks if the user closed the browser after by ajax sends a server-side program to save.

  • Actually there’s a way you can do a kind of a check, I don’t think it’s a scam... you check if the user is too long inactive, if it’s + than a certain amount of time you stipulate for a user to be inactive, then you give a meta refresh to the page and send it to the server to move this account

  • For example: <meta http-equiv="refresh" content="600; url=suapropriapagina.php?action=deslogar">

  • Good evening Leo, I wonder if any of the answers helped you, if not please comment on what you think is missing.

2 answers

5


In a short answer Is not possible send a request as soon as the browser window is closed to instance of it is destroyed and has no way to send a request in time for the back-end.

The best way, as instructed in this question is to create a "timer" for the user session and this I believe is the best method, aiming that the Google Analytics uses a similar technique.

Let’s assume you have a table in the user database

id | login | senha | nome | lastactive
-----------------------------------------------
1  | test  | test  | João | 2015-06-24 01:00:23
-----------------------------------------------
2  | maria | maria | Maria| 2015-06-24 01:00:33

You will need to use a minimum amount of activity time in the PHP layer to define whether the "user is online".

With each user request test (assuming you are logged in co), you must execute a update in the table for the id his:

 UPDATE usuarios SET lastactive=CURRENT_TIMESTAMP WHERE id=1

To display this user to other users (for example if it is a chat) PHP should be something like:

define('REQUEST_TIME', $_SERVER['REQUEST_TIME']);
define('TIME_ONLINE', 120);//120 = 2 minutos

function isOnline($timer) {
    return REQUEST_TIME - strtotime($timer) > TIME_ONLINE;
}

$query = 'SELECT nome, lastactive WHERE 1 ORDER by nome';
if ($result = $mysqli->query($query)) {

    while ($row = $result->fetch_assoc()) {
        echo 'Usuário ', $row['nome'], ' está ',
             (isOnline($row['lastactive']) ? 'online' : 'offline'), '<br>';
    }

    $result->free();
}

In this example, if the user is not performing an activity for more than 2 minutes, it is considered "offline" for other users or any other action, just use the function isOnline, if it’s TRUE can execute a command on the user as it is online, if it’s FALSE it is "offline", so you can ignore or vice versa, will depend on what you want to do with online/offline users.

1

Currently I did not find any elegant way to check when the user closes the browser to open the possibility of another connection, so I use another methodology to solve this problem, let’s see.

1° Log in

when the person logs into the system you validate making a select user and password and if positive creates a session for it to stay logged in right? you can create two idnet and datePath fields in the database and update it with a key and the current date. (idnet - key) is to identify which session you are using you can create like this:


function geraidnet() {
   $idnet = rand();
   $idnet = mb_strtoupper(md5($idnet));
   $_SESSION['IDNET'] = $idnet;
   return $idnet;
}

$idnet = geraidnet();

The dateAccess is to check the time that the person is idle. You can reset the idnet and dateAccess when the person is idle, for example for 5 minutes:


 $sql = 'UPDATE USUARIOS' . "\n" .
        '   SET DATA_ACESSO = NULL ,' . "\n" .
        '       IDNET = NULL' . "\n" .
        ' WHERE DATA_ACESSO menorQ (CURRENT_TIMESTAMP - 0.00347)';

All users who have been idle for 5 minutes in the system will have their idnet and dateAccess reset now you can select to check how many users are logged in.



$sql = 'SELECT COUNT(0) AS QUANT_UL' . "\n" .
        '  FROM USUARIOS' . "\n" .
        ' WHERE DATA_ACESSO IS NOT NULL';

if (($result = $db->Execute($sql)) == false):
   throw new Exception($db->ErrorMsg());
endif;

if ($result->fields['QUANT_UL'] menorQ 10): // só pode haver ate 10 conexões
   $sql = 'UPDATE USUARIOS' . "\n" .
           '   SET DATA_ACESSO = \'' . $data_acesso . '\',' . "\n" .
           '       IDNET       = \'' . $idnet . '\'' . "\n" .
           ' WHERE id      = ' . $idusuario;
else:
   throw new Exception('O número máximo de conexões foi atingido!');
endif;

All you need to do now and update the user’s dateAccess when it performs some operation on your system.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.