2

I am trying to refresh page automatically when session times out. I have look other post but I think we are not same problem.

I have the session out code:

$inactive = 10;
if( !isset($_SESSION['timeout']) )
$_SESSION['timeout'] = time() + $inactive; 

$session_life = time() - $_SESSION['timeout'];

if($session_life > $inactive)
{  session_destroy(); header("Location: http://localhost/fmsgroup/fmsystempanamed/logout/endsession.php");     }

$_SESSION['timeout']=time();

what will I add so that when it refresh it will go to the header.

Siva Gopal
  • 3,474
  • 1
  • 25
  • 22
shiro Jacinto
  • 155
  • 1
  • 12
  • what do you mean by `what will I add so that when it refresh it will go to the header.` – iam-decoder Nov 09 '15 at 07:29
  • What is `$inactive` ? Is it in seconds or minutes? – AnkiiG Nov 09 '15 at 07:35
  • Good day sir.. i want to know what will i add with my code so when session out then it will refresh sir.. it will go to http://localhost/fmsgroup/fmsystempanamed/logout/endsession.php – shiro Jacinto Nov 09 '15 at 07:37
  • Not sure if I understood your question correctly, however, `header("Location: http://localhost/fmsgroup/fmsystempanamed/logout/endsession.php");` behaves as a page refresh already. Maybe, your problem is in the logic of determining the timeout session, is it? Elaborate more so we can determine the real issue. – missing_one Nov 09 '15 at 07:43
  • sir... how to automatically refresh the page when the session times out... what will be my code? in that code.. when session time out... when user click some button that is the time page will refresh... how can I sir... refresh it automatically? – shiro Jacinto Nov 09 '15 at 07:50
  • you have to use javascript to automatically reload the page. for this you have to store the session timeout somewhere and after this time redirect to the right page. – Raphael Müller Nov 09 '15 at 07:56
  • so i will search some forum... how to automatic reload page when session time out using javascript? – shiro Jacinto Nov 09 '15 at 08:01
  • take a look at: http://stackoverflow.com/questions/15719729/i-want-to-load-another-html-page-after-a-specific-amount-of-time – Raphael Müller Nov 09 '15 at 08:05
  • sir when i look that.. it refresh tha page.. how can i combine it with the condition that when session times out.. it will refresh – shiro Jacinto Nov 09 '15 at 08:09

3 Answers3

1

I think that the best option is AJAX. You can create an interval on the page, that will send a request to the server.

The javascript part will be placed inside your BODY section of the html document:

<script>
function keepAlive() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          if (this.responseText === "pong") {
              // session refreshed
          } else {
              // something wired happened
          }
     }
  };
  xhttp.open("GET", "ping.php", true);
  xhttp.send(); 
}
// set an interval that runs keep alive every 10 minutes
setInterval(function() {keepAlive()}, 600000);
</script>

then you will have the ping.php file that responds to the request

<?php
session_start();
echo "pong";
?>
Cosmin Staicu
  • 1,809
  • 2
  • 20
  • 27
0

It depends on your session implementation.

  1. file-based

There is no expire hook or callback event, so you can only use ajax polling, which ,in your case, server will redirect the page

  1. redis-based

redis 2.8+ has keyspace notifications, so if you watch your session database, you can get notified when session expired.

BUT, this would be an expensive solution. Because you have your PHP process blocking to wait the event, NOT RECOMMENDED.

Or there may be another one:

Set your session.gc_maxlifetime equal to session.cookie_lifetime, so when the session expire, the cookie should expire at the same time, so js won't have to poll from server, instead, it can check the local cookie periodically.

Nowhy
  • 2,894
  • 1
  • 16
  • 13
  • sir can site some sample code just like with my code.. when session time out.. it will auto refresh... because.. when session is out.. the page was not reload.. – shiro Jacinto Nov 26 '15 at 01:59
0

Edited order so it would now work!

I know this is an old post but I searched and did not find an easy answer. I am posting here for anyone else who looks . This is a pure PHP solution. I have seen so many posts that say you can not do this in pure PHP and that is incorrect. I had given up on a PHP solution then it hit me like a brick.

I use a minimal session login time , we will say 1800 seconds (30 minutes) This gets set in $_SESSION['expire'] this is set as ($now + 1800)

$now=time();
$_SESSION['expire'] = ($now + 1800);
$timeremaining=($_SESSION['expire'] - $now);
$buytime=1800; // sets how much time we add with a page refresh/load
$addtime=900;  //sets at what point we add time with a page refresh/load. 
//In this example a page reload will not add time ($buytime) until we reach 900 
//or less seconds remaining. at which time we will add 1800 seconds

once the $_SESSION['expire'] shows 15 minutes (900 seconds) from current time, we can now $buytime with a page refresh, or loading another page (with $buytime code). Once we reach the 15 min or 900 seconds before session times out no page reload will add time until we fall below 15min 900 seconds again. If someone is not loading a page every 15 minutes they should get their login timed out.

if ((($_SESSION['expire'] - $now) <= $addtime) && (($_SESSION['expire'] - $now) > 0))
{
$_SESSION['expire']=($_SESSION['expire'] + $buytime);
$timeremaining=($_SESSION['expire'] - $now);
}

Now because I do other things with the refresh like go back to login screen if login is invalid, I set the following in the as a variable. in this case we are assuming a valid login

$refreshurl='<meta HTTP-EQUIV="REFRESH" content="'.$timeremaining.'; url=login.php">';

We can now build the page content using the $refreshurl variable above. A PHP Page refresh will now occur at $timeremaining after last page load and force us back to the login page because we echo $refreshurl into the page header, also force a reset of all session variables, just in case.

<a href="'.$_SESSION['pageurl'].'">

The PHP above does carry through the URL Variables, or if you want the javascript which will even maintain page anchors (which did give me trouble on first load of the page that does the actual php authentication and sets the timer).

<a href="javascript:history.go(0)"> 

With this solution, reloading the current page adds time, or loading a new page adds time. If updated with a page refresh or newly loaded page (with similar code) , the header is updated too. setting the new page refresh time.

Now the page is refreshed and the new header is written with the new expire time in seconds counting down ($refresurl gets set after applying $buytime and resetting $timeremainiing. When it counts down to 0 the page reloads the login page. Also on the login page I unset all session variables then destroy the session at the beginning. I also use multiple checks in all pages to ensure that a session is not expired and a valid user is logged in with a valid password. The page refresh is clearly not enough. The security code is not included here!

I also run a javascript tool (below) to display time remaining and when session timer reaches 0 or current time the php wrapper for that javascript also destroys the session.

checklogin.php

session_start();
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$now = time();
$logininsec = ($_SESSION['expire'] - $now);  //gets remaing session in seconds
$loginrefresh=60 to update the dynamic page data every minute
// makes $loginmessagetxt appear on page dynamically using Javascript
if (( $requireauth == 'yes' ) && ( $_SESSION['loggedin'] == 'yes' ) && ( $_SESSION['expire'] > ($now + $addtime) ))
{
$loginmessagetxt='<span style="color:#080; font weight:bold">Session expires in '.round(($logininsec / 60),  0, PHP_ROUND_HALF_DOWN).' minutes</span>' ;
}


else
{
$loginmessagetxt='<span style="color:#F00; font weight:bold">Session has expired</span></td <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/login.php"><span style="color:#777AFF; font-weight:bold">'.$login.'</span></a>'; 
session_unset($_SESSION["loggedin"]);
session_unset($_SESSION["expire"]);
session_unset($_SESSION["username"]);
session_unset($_SESSION["password"]);
session_unset($_SESSION["userpath"]);
session_destroy();
$loginrefresh = '7200';  //this just keeps the javascript from running so frequently when logged out
}
echo "retry: $loginrefresh\ndata: {$loginmessagetxt}\n\n";

then on the page we also need the following to display login time remaing

echo "<td><div id=\"loginStatus\">Checking Login Status</div></td>";

with the following script support

<script type="text/javascript">
if(typeof(EventSource)!=="undefined") {
    var statusSource = new EventSource("checklogin.php");
    statusSource.onmessage = function(event) {
            document.getElementById("loginStatus").innerHTML = 
event.data;
    };
}
else {
    document.getElementById("loginStatus").innerHTML="Unsupported";
}

So although I do use some Javascript in my solution. The base solution can be used with NO javascript support. That is unless you want to display time remaining dynamically.

I might also addd that I have a tendency to write 100s of ways to destroy the session in my other code too, as I doubt much of this is very secure. There are many ways to get around page refreshes and running the javascript.

Mark
  • 39
  • 1
  • 6