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.
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.)?
– user25930
by javascript there is onclose method that checks if the user closed the browser after by ajax sends a server-side program to save.
– Ângelo Rigo
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
– MarceloBoni
For example:
<meta http-equiv="refresh" content="600; url=suapropriapagina.php?action=deslogar">
– MarceloBoni
Good evening Leo, I wonder if any of the answers helped you, if not please comment on what you think is missing.
– Guilherme Nascimento