Session Management – Managing Session Timeouts Based on User Activity

ajaxjavascriptPHPSecuritysession

So I will be creating a feature to a php application that does the following:

  • Create a session that expires after 30 minutes.
  • After 30 minutes, if there is no user activity in the application (including typing to a textbox, moving a mouse throughout the page), the session will be destroyed and the system will redirect itself to a logout page (logout.php). What I mean by keyboard/mouse is only specific to the system, if the system is open while I am doing other things outside of the system, the system should consider it idol.
  • If the session has moments left to live (E.G. 15 seconds) and there is user activity, the session's life would be extended to another 30 minutes. The reason for this is if a user is inputting a critical information, it would be highly inconvenient to log him/her out just before submitting the form. This is why keyboard and mouse movements should be detected by the system.

I have come up with two possible solutions, but I am not satisfied with them.

First solution

I will almost use javascript for everything.

  • Manage the session or cookie (I am not really sure if javascript recognizes server side sessions)
  • Detect keyboard/mouse activity
  • Extend the life of the session/cookie
  • Redirect to logout.php to destroy the session

I believe this solution is extremely bad. I believe there are ways to manipulate javascript code to change it (to prevent the redirection to logout.php, for example). That is, I am doing a process that should be done in the server.

Second solution

  • use javascript to detect keyboard/mouse activity as before.
  • 15 seconds before 30 minutes, I will have to send an ajax request to a php page. The ajax request contains the information whether there is user activity during this time.
  • Now this particular php page manages the information sent by ajax. If user activity is detected, php just extends the session's life. Otherwise it has to redirect to logout.php either through ajax's .done function or through other means.

I don't think the processes I described above are good solutions. Specifically the heavy use of javascript to do server side things. My problem is I cannot find a way to detect keyboard/mouse movements using php. Everything I found regarding how to do this is by using javascript (understandably since user actions are done in the browser and not in the server).

How should I proceed? What would be the best and most secure solution?

Best Answer

Your second solution is best solution. I believe this because it should fundamentally be the clients responsibility to inform the server that they are still active. The server can then do as it must from there.

This gives the server all the control over what happens. The only control the client has is to designate if the user is still active or not. Which is a proper client/server relationship.