Reputation: 1114
I am having an PHP application which keeps session tracking. I want the application to keep user session until he close the browser. The session should not expire until the browser is closed. I am a java developer and I am novice to PHP.
Session should not time out before browser is closed. Session will time out after sometime once browser is closed anyway.
Upvotes: 0
Views: 3260
Reputation: 1158
I know this question is a little old but since it's still relevant here's how I do it:
function keepMeAlive() {
var img = new Image();
img.src = YOUR_URL + 'images/empty.gif?' + new Date().getTime();
}
window.setInterval(keepMeAlive, 600000);
Now create a 1x1 pixel gif image and upload it to the specified URL. The above code will load it once every 10 minutes, thus keeping your session alive.
Upvotes: 0
Reputation: 14222
It is possible to use Javascript to detect when the page or browser window is being closed. However this should not be relied upon, because there are plenty of ways for the user to stop browsing the site without that notification ever being raised (a browser crash, network or power outage, etc).
The standard answer is not to bother with this kind of thing -- PHP sessions have a timeout mechanism anyway. If the user doesn't load any pages in a given time period, the session is deleted. This is standard, and you shouldn't need to worry about it. The only thing you might want to do is adjust the timeout duration according to how you expect your users to use the site.
If you really want to keep an eye on the users and make sure they're still actively on the site, and terminate the session as soon as they stop, I guess you do something like write a simple Ajax ping, so that the page sends a request to the server every few minutes (or whatever interval you want).
This would keep the session alive, even with a fairly short session timeout, until the browser stopped sending pings (which could be because the browser window was closed, but also if the browser crashed, or the network connection went down, or the user pulled the power plug, etc).
The down side of this is that it would create quite a lot of extra traffic to your server (and quite a lot of extra work for you), with no real benefit over simply letting the sessions timeout on their own.
Upvotes: 1