'session timeout due to inactivity + alert box

i am looking for solution of my answer which is half completed i have to make the user logout from my website and i used your solution which is as follow:-

if( $_SESSION['last_activity'] < time()-$_SESSION['expire_time'] ) {

 //have we expired?
    //redirect to logout.php
    header('Location: '.BASE_FULL_PATH.'/user/logout'); //change yoursite.com to the name of you site!!
} else{ //if we haven't expired:
    $_SESSION['last_activity'] = time(); //this was the moment of last activity.
}
$_SESSION['logged_in'] = true; 
$_SESSION['last_activity'] = time(); 
$_SESSION['expire_time'] = 24*60*60;

and it is working perfectly but i need to have an alert box when the session is about to expire.Try lot of stuff but doesn't help.Please reply and thanks for your brilliant demo

php


Solution 1:[1]

I know , this is not an efficient way, But you can try this. try ajax, that runs a php file in server every 5 or 10 second time gap.

that ajax running php file contains session last_activity and expire_time comparing code,

<?php
$warning=100;
if( $_SESSION['last_activity']+warning < time()-$_SESSION['expire_time'] ) {
?>
<script type="text/javascript">
alert("Your session will expire soon!");
</script>
<?php
}
?>

You can set the variable $warning to adjust the alert message time.

Solution 2:[2]

Since your session expiry will reset every time you reload the page, then you can use the expiry time as the time argument of JavaScript's setTimeout() function.

var sessionExpiryTime = 24 * 60 * 60;
var sessionExpiryAlertTime  = sessionExpiryTime - 5; //assuming we want the alert to show 5 seconds before expiry
setTimeout(function({ 
    alert("Session about to expire!");
}, sessionExpiryAlertTime * 1000); //time is in milliseconds so we multiply by 1000

This works okay as long as the user has JavaScript enabled. If the user reloads the page, the expiry timer updates as per your php code and the setTimeout() function restarts.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 anu g prem
Solution 2 Richard