tinks
tinks

Reputation: 323

Setting sesstion timeout due to inactivity

I am currently working on session timeout. During inactivity in my page for a specific time, the session should time out and goes back to the login page.

I have this code.

// set timeout period in seconds
$inactive = 30;
// check to see if $_SESSION['timeout'] is set
$logger->debug("root|DEBUG3 accdetails_proc");
if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive)
    { 
        session_destroy(); 
        header("Location: ../../index.php");
             ///OR
        //echo('<script type="text/javascript">');
        //echo('top.location.href = "../../index.php"');
        //echo('</script>');  
    }
    else{ }

Both the header and echo are not working. When it times out, it stops in the session_destroy() and still executes the callback, because I am calling this file using ajax.

If i use "echo" the response is:

<script type="text/javascript">top.location.href = "../../index.php"</script>');  

which when parsed in my callback gives out the error already.

if I use the "header" it returns the html of my login page but executes first my callback so it still gives out the error and the login page is not loaded.

Can somebody help on how to not execute the callback of ajax when you destroy a session?

Thanks

Upvotes: 1

Views: 1724

Answers (2)

nbhatti2001
nbhatti2001

Reputation: 363

You have need to add the same logic in ajax which you have use in header file. send time out response to call back function and in call back you may show an alert and then redirect the brower according your requirement.

Upvotes: 0

chiborg
chiborg

Reputation: 28074

If you are using an Ajax callback for checking if the session timed out, you need to handle the redirection to the start page in the handler for the Ajax data.

Your PHP could look like this:

if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive)
    { 
        session_destroy(); 
        echo "LOGOUT";
    }
}
echo "OK";

You JavaScript code on your page could look like this (assuming you use jQuery):

$.get('http://example.com/my_session_check.php', function(data){ 
  if(data=='LOGOUT') {
    top.location.href="../../index.php";
  } 
});

Upvotes: 1

Related Questions