27 Aug

keeping an admin session active

I had a call from a client who asked why, after logging into a CMS admin area and spending an hour or so writing a document, she was unable to submit it because it claimed she was not logged in.

The answer was that the session had expired.

On busy servers, one method of optimisation is to reduce the session-time. This makes it easier for the server to cope with a large number of visitors, but also has the undesired effect of logging people out if they take their time over anything.

One solution to this is to keep the admin session in a database table, tied to a cookie in the browser. Unfortunately, that means that every time the browser sends the cookie, it must be verified, whereas a session is usually trusted.

The workaround is to use some JavaScript to refresh the session every now and then.

I wrote a simple cyclical script which polled the server every minute to refresh the session.

Here it is, using jQuery to handle the AJAX:

function keep_session_alive(){
  setTimeout(keep_session_alive,60000);
  $.get('/ww.admin/keepalive.php');
}
setTimeout(keep_session_alive,60000);

And the server-side code is this:

<?php
session_start();

Very very simple trick. The polling could be enhanced, if you want, to alert the admin of anything interesting that’s happened on the server.

2 thoughts on “keeping an admin session active

  1. Hello, I apologize if this is the wrong place to comment. I was looking at your caching solution for .js files. I believe that I can solve my issue by destroying a session and opening a new one, but I don’t to that for other reasons. Specifically, I have a graph on a page which is generated by PHP. The user can change the graph by hitting various buttons to see different things on the graph. I use ajax and a php function to recreate the image (graph) and it works just fine. Unfortunately, the image will not display on the screen until the page is refreshed, defeating the entire purpose of using ajax. I’ve tried all the no cache settings, preloading the image in my oneadystatechange function, I’ve removed the img element and re-added it. Nothing works, only the cached image remains until refresh. Can your modrewrite cache solution help me here? Each user has his own graph so the solution has to work for all the files in a certain folder (/media/images/generated). Any pointers would be appreciated. Thank you. Again I apologize if this is the wrong place to ask.

  2. hi Colin – try changing the image address to use a ?5327183t1 after it (randomly generated).

    For example, if the graph is /images/graph.jpg and has been updated, change the page’s <img> tag to reference it as something like src=”/images/graph.jpg?”+Math.random()

Leave a Reply