CoderZone.org
Pages: 1 « previous     next »
  Print  
Author Topic: Cheesy, sleazy trick - avoid session timeouts  (Read 19918 times) Bookmark and Share
Max
Jr. Member
*****
Posts: 75



View Profile WWW
« on: Mar 24, 2011, 12:30:50 pm »

I can't remember where I saw this, but it was so simple and so sleazy I had to copy it in case I might want to use it. Smiley

Basically it's a way to avoid session timeouts without mucking about with the session ini settings or gc_ variables. At the bottom of the page you want to "keep alive", place a small IFRAME and a little bit of javascript, like this:

Code:  
Highlight Mode: (HTML)
  1. <iframe id="kp" src="/keepalive.php" style="width:1px;height:1px;"></iframe>
  2. <script type="text/javascript">
  3. function keepAlive(){
  4. if(refreshCount <= 1000){
  5. var kp = document.getElementById('kp');
  6. kp.src = kp.src;
  7. setTimeout('keepAlive()',600000);// run every xxxx milliseconds
  8. // inc the refresh counter
  9. refreshCount++;
  10. }
  11. }
  12.  
  13. keepAlive();
 

On the server, place this code in "keepalive.php":

Code:  
Highlight Mode: (PHP)
  1. <?php
  2. print date('Y-m-d G:i:s');
  3. ?>
 

The javascript will run every xxxx milliseconds (every 10 minutes in the example above) and refresh the IFRAME. This will run "keepalive.php" on the server and refresh the session (it also prints the time and date to the IFRAME page, but that's hidden by the IFRAME's CSS).

The "if(refreshCount <= 1000){ " line in the javascript can be used to eventually timeout the session by preventing the IFRAME from refreshing after whatever count you want (and since the number can be changed dynamically, it could also be used as a user-settable configuration parameter).

Again, this is so sleazy that I laughed when I first saw it, but after looking at it I decided that it was actually a crude but valid solution to a session time out problem. Elegant? Not terribly, but it works and honestly I can't find anything that's really "wrong" with it.
Logged
Keith
Newbie
*
Posts: 11


View Profile
« Reply #1 on: Mar 24, 2011, 03:57:02 pm »

I've incidentally done this before with an AJAX-ified real-time `online users` counter.

It accomplished the same thing while actually serving a purpose. Wink

It also avoids the `Loading xxx.com/keepalive.php` (or similar) message in the status bar every X number of seconds/minutes.
« Last Edit: Mar 24, 2011, 04:07:08 pm by Keith » Logged
Tags:
Pages: 1
  Print  
 
Jump to: