aosh5
aosh5

Reputation: 89

session_destroy() with JavaScript

I'm looking for a JavaScript code to destroy the session of users which aren't active. (It's for a live chat site)

Expiry: The website detects every 5 minutes the activity of a user and then it updates the database with the last activity timestamp. So if the user didn't wrote since 2 minutes ago, the last activity timestamp would be time()-120 (120=2minutes)

And now I will that a js code can detect if the last activity timestamp is more than 300 seconds (5 minutes in seconds) ago, to destroy the session of the inactive user.

With php it would be easy, only it would need a refresh of the page and then the user would be logged out. Is there a chance to do this with javascript without refreshing the page? If inactive -> destroy session and automatically logout, so the user can't write anymore.

Thank you.

Upvotes: 0

Views: 1120

Answers (1)

Kaivosukeltaja
Kaivosukeltaja

Reputation: 15735

The session is a backend concept and can not be directly controlled with frontend Javascript. Sessions refer to information that is stored on the server and linked to the frontend user in some way, usually with a session cookie.

What you can do is either remove the cookie and wait for the session to die on the server, or write a PHP script that invalidates the session immediately and call that over AJAX. Either way, you'll have to change the UI with Javascript to let the user know they've been logged out, for example by disabling the text inputs and halting the script that polls for new messages.

Please also note that terminating the session for an idle user without warning is bad UX and will annoy your users. At least give them a notice beforehand that their session will be dropped in two minutes because of inactivity so they can react to stay online.

Upvotes: 1

Related Questions