Reputation: 111
I have a web app that use ajax and execute every 10 seconds to update some data. I set a PHP session that after 60 minutes of inactivity the php session dies and kick user out of the page, but in this page the session never expire, I guess this is because the Ajax call execute every 10 seconds and the server refresh the "timeout", my session works fine in other pages where I don't execute ajax. You guys think that my problem in this page is because the ajax calls every 10 seconds?
My Jquery code:
delay(function(){
check();
}, 10000 );
function check()
{
$.ajax({
dataType: "json",
url: "lead.php",
cache: false,
success: function(msg){
//Do something
}
});
}
Upvotes: 0
Views: 576
Reputation: 820
I guess lead.php
uses session_start()
. You could remove it only in that file.
Or, on first initialization, save the current time to a session var, and then for each call, check if more than one hour has passed. If true, session_destroy()
Upvotes: 0
Reputation: 1709
If you wants to close the session after X time, no matter if the ajax requests are being made, but only if the user has no activity on the page, you can use this code I'm using:
(function () {
// After 30 minutes without moving the mouse, the user will be redirect to logout page
var time2refresh = 30;
// This is how many time the user has to be inactive to trigger the countdown of 30 minutes
var timeInactive = .5;
// This will store the timer in order to reset if the user starts to have activity in the page
var timer = null;
// This will store the timer to count the time the user has been inactive before trigger the other timer
var timerInactive = null;
// We start the first timer.
setTimer();
// Using jQuery mousemove method
$(document).mousemove(function () {
// When the user moves his mouse, then we stop both timers
clearTimeout(timer);
clearTimeout(timerInactive);
// And start again the timer that will trigger later the redirect to logout
timerInactive = setTimeout(function () {
setTimer();
}, timeInactive * 60 * 1000);
});
// This is the second timer, the one that will redirect the user if it has been inactive for 30 minutes
function setTimer() {
timer = setTimeout(function () {
window.location = "/url/to/logout.php";
}, time2refresh * 60 * 1000);
}
})();
So the logic of this function is this:
1) User log in into your site 2) After .5 minutes (30 seconds) of inactivity one countdown of 30 minutes will start 3) If the user moves his mouse, both timers are reseted, and the first one start again. 4) If after the 30 minutes the user does not moves his mouse, then it will be redirected to the logout page, closing his session.
Upvotes: 2