M
M
Matthew Stafford2018-10-25 16:50:48
PHP
Matthew Stafford, 2018-10-25 16:50:48

How to kill a session after closing a tab?

Hello!
How can I kill the session when the tab is closed?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry Kuznetsov, 2018-10-25
@matthewstafford

The session is stored on the server. As an option, you can do this:
1. The user has a session for N minutes.
2. When a user does something on the site (follows links, writes in comments, etc.), i.e. it's online, you renew the life of the session.
3. When the user closes the tab, the session remains on the server. Do not forget about 1-2 points.
4. As soon as the user visits the site again after N minutes, we check if there is a session storage time for this user. If not, then delete the session. And if there is, then we overwrite it again.
Also, in addition, you can add CRON. It checks the session, and if the session lifetime is less than the time now+N minutes/seconds (point 1), then it deletes it. Otherwise, do not touch.
Something like this. I hope my answer will lead to something more!

D
dollar, 2018-10-25
@dollar

JS:

window.addEventListener("beforeunload", function(e){
   // Сделать что-то. Например, ajax на сервер.
}, false);

And on the server, additionally interrupt the timer.

T
ThunderCat, 2018-10-25
@ThunderCat

There is no 100% way to check if the client has closed the tab, the only thing you can TRY is to send an Ajax request to the server to logout/destroy the session on the onbeforeunload event.

S
Stalker_RED, 2018-10-25
@Stalker_RED

How can I kill the session when the tab is closed?
You have php tags there, so I will assume that you are talking about these sessions.
Answer: none .
PHP does not know what happened to the user: maybe he closed the tab, or closed the lid of the laptop, or drove into the tunnel, or his computer was frozen, or the Internet was turned off for non-payment.
You can add the beforeunload trick as suggested by dollar , but this is no longer a pure PHP solution. Well, false positives are possible when several tabs are open. Additional checks will have to be done.
You can also not set the session cookie Expires, and then it should be deleted by itself when the session is closed by the browser, but ... there are browser settings and plugins that allow you not to break the session when you close the tab and never at all.
Therefore, I propose not to suffer, and simply set the session lifetime that is convenient for you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question