Home > Back-end >  Checking User Session in PHP
Checking User Session in PHP

Time:09-29

Is That a Good Approach to Send AJAX Request every 10 seconds to check the user session in PHP? or any other method to check a user session and if the session is expired then do a logout for a user automatically.

CodePudding user response:

Add a countdown timer to the frontend. Set its start value to the session timeout value. When its value gets zero, make a request to the backend. If timeout exceeds, redirect the user to the login page. Else, set the frontend countdown timer value to the value in the response.

CodePudding user response:

Always bear this in mind when programming for the web:

Client for Convenience, Server for Security

Everything that runs in the user's browser (the client), or is sent from there, is completely under the user's control. Only code that runs directly on your server, and data that never leaves your control, can be relied on for security.

So the answer really depends what you're trying to achieve:

  • To communicate to the user as soon as possible that their session is ending? That's convenience, so your approach of a JS timer on the client would make sense. A request every 10 seconds might end up with a lot of load on your server, though; you might want to make the timeout a bit longer.
  • To make sure the user can't continue interacting with the website after the time limit? That's security, so your approach won't work. The individual actions on the server need to verify whether the user's session is still active.
  • Related