Automatic session timeout in php - session

Im doing session timeout with php. Im calling php
through ajax. After X seconds of inactivity, if a user
sends a request it is redirected to login page as session has already expired.
How do I send a session timeout message back to browser automatically
and not waiting for a request trigger?
Like, I should have a thread running in the background to check the time
always? Do you have ideas guys?
Thanks a lot.

Sending a request from the server to the browser via ajax is known as long polling, or "comet". It is a proven technique, but now without pitfalls.
For one, a connection need be kept open for each user. That's a lot of overhead, so it should be done with something like NodeJS. Even so, the long poll need be reset every 20s or so, which result in fickle code. Newer browsers introduce websockets, which improve things but require a framework with fallback mechanisms. The question is whether it's worth it for your application.
What I would do in your situation is implement the same timeout mechanism in JavaScript. That way, the user gets a nice message when the session times out in JavaScript, and the server enforces the timeout in case the user bypasses the browser for some reason.

Related

How to handle session timeout when a device was suspended in an Ajax app?

It's easy enough to build an Ajax app which checks all responses to make sure they aren't indicative of a session expiry, and if the session has expired automatically log the user out with a friendly "Your session timed out due to inactivity" error message.
But a common occurrence in Ajax applications is that:
User is logged in, happily using app, retrieving data over http with an established http session
User closes laptop
Host times out http session after N minutes
User reopens laptop later on. Ajax app appears alive and well. They click around which is just fine since the app lets them see things they've already loaded.
Then, they click on something that requires data to be loaded, and the data comes back indicating session expiration
The Ajax app kicks them out and says "Your session timed out due to inactivity".
This is really weird to the user because they were not inactive from their point of view.
Now, one possibility is to have Javascript code in the client which uses setTimeout() to periodically (say, every 15 minutes if the session timeout is 30 minutes) trigger a request to the host to ask how much time is left in the session. This periodic check is great because it lets you show them a warning when they are close to timing out, e.g. "You're session will time out in 1 minute unless you do something".
But that doesn't help when the user's machine is suspended. That's because according to all my testing in many different browsers, setTimeout time applies to elapsed running time instead of elapsed real time. That is, if you call setTimeout("alert('hi')",2*60*1000); and then suspend your machine 10 seconds later, wait 5 minutes, and reactivate your machine, you'll have wait 110 more seconds until you get that alert (I have not been able to find definitive documentation of this behavior but it is a demonstrable fact). So that means your period check may not happen for quite after the user's machine resumes.
My solution to this is to, instead of having my periodic check based on on a long setTimeout, instead do a short setTimeout (say, every 5 seconds), and check the elapsed time since the last check using new Date().getTime() to get the actual clock time. This way I am always checking against the real clock, and instead of the client waiting from zero to fifteen minutes before realizing it has timed out after a suspension, at most it will wait about five seconds (plus http response time) to find out.
But I dislike this solution because it relies on a frequent timer based interruption. Is there a smarter way to handle this?
With big sites like facebook, which is rich with interactive updates, you'll find that there is a combination of all sorts different mechanisms. I'd guess that they're doing validation both on API requests and on Push requests (since someone once told me they use push in addition to ajax)
Timeouts: One thing to consider is that if you store session data in a cookie, having that cookie expire is the same as no longer being logged in. Since the cookie is a hashed value of a few things like a user ID, or a timestamp, it is really easy to see that a session is no longer valid on the very first function call to the API.
Long polling: if a site uses long polling in which a connection is opened indefinitely to await a response from the web server, then closing your computer would kill that connection.
However, if they're just doing regular ajax polling with a reoccurring function call via setInterval, then the web server would automatically know whether the user should get data in return based on the timestamp in their hashed cookie, assuming there is one to check. Those are the types of things that get sent in the header.
Some services actually update a database field that stores your timestamp of last activity and then expires if a certain amount of time has elapsed. This is a less efficient way to do it since it keep track of state.
There's really quite a few ways sites do these things.

Timeout behavior of different browsers?

I am writing an on line chat room based on AJAX/COMET. My design is:
Request
----------------- wait -------------------------> send dump data
----------------- wait -------------------------> send dump data
----------------- wait -------------------------> send dump data
----------------- wait -------------------------> send dump data
----------------- wait -------------------------> send dump data
------ something happened, get response.
Another request
.....
....
As you see, the server hold the request and wait something happened, if there is some event happened, just push data and finish request. Then the client will issuse another request.
There is tick in request, so if there is event happened betweenhe t gap of two requests, server knows that there is pending event for the client.
Before the browser timeout, the server also send some idle data to prevent client from timeout.
Now, here comes the problem: what are timeout behavior of different browsers? I know that browser sends request and wait for data, if it take too long time to wait, it will timeout. But what are those timeout behavior of different browsers? And are there any header that can control the timeout behavior of browser? By knowing the timeout behavior of browsers, so that I can decide how to deal with them. Where can I find those data?
Actually, since the client could be going through proxies, the explicit values of the timeouts for different browsers don't mean as much as you'd think.
Rather, I'd ask why you're asking - you're going to have to deal with timeouts, and no amount of streaming to the browser is going to prevent it every time. So it'd be best to simply requery the server from the client when the connection drops - which is one reason why a lot of people recommend long polling which is what you seem to be trying to do. Regardless of whether you choose a streaming solution or a long poll, you have to allow for connection resets.
For a simple hidden iframe client setup, it's not too hard to do - and it's equally easy for XHR requests, depending on what client side framework you're using.
The timeout for most modern browsers seems to be rather large in IE (60 minutes? Wow), and shorter in FF (about:config says 300 seconds - eek) - but as I said, that doesn't help you against a proxy, where the timeout could be as short as 2 minutes or less, depending on how the proxy admin configured it.
So, in summary - timeouts happen. You can't stop them. Code your client to reconnect when they happen (with a limit to prevent a spin on server down), and don't worry about it further. Besides being more robust, it'll probably also make your code more performant, since you won't be periodically pumping useless data to every client.

Session timeout in web applications

The session timeout in web applications typically denotes the idle time - i.e. the period of time when the user doesn't work with the application.
Now, what if there is an automated script written that posts a request every 5 minutes - wouldn't that user's session go on endlessly? This being the case, won't this approach heavily load the application affecting its performance in the long run?
Running an automated call to the server, say via an AJAX request, will keep the session alive. Typically that's the point though. An interesting side effect of this is that if the request happens predictably and regularly, you can use it as a "ping" to determine if the user's browser is still open. If one or two pings are missed, you can close the session earlier and actually free up resources sooner than if you just let the session time out.
Yes, and Yes.
This is why if you're going to write an application for the web, you really want to find a way to implement it without using server side sessions. Usually, you will be able to find ways to implement the same functionality using cookies -- then the session data is client-side so who cares if they stay active permanently.
I did something similar for an application that relies heavily on session data.
What I did was set the IIS timeout to a relatively low number, say 10 minutes, then have a timed AJAX call that pings a blank page every 5 minutes.
This overhead on this is actually fairly low, as all you are doing is requesting a blank page, and if a person closes their browser, the session ends in 10 minutes.
You want to keep session as small as possible. That said, if everyone starts doing that, of course it will load your application, with(out) session. If you think your users are compelled to do that, consider why, as either your application is missing an important feature or is forcing them into something.
Now, regardless of that, if you are expecting lots of users to be active at the same time, so much than a single server won't do, then you would will end up having the session out of process. If the session is in Sql Server, it is just saved data, so in that case we wouldn't be talking about memory usage.
Well... I guess "It Depends" The first question you should ask yourself is whether you even need session.
If you have an automated process, my guess is that you don't really need to use session.
In that case, either turn it off or don't worry about it.
I guess your session table would be a little bit larger, but on the other hand you won't be tearing down and recreating the session. I don't see how this would "heavily load" the application. I suppose it would depend on the application itself and how much memory is used to maintain session state.
It would allow the use's session to go on endlessly, as long as they have their browser open. If need to keep a session alive for an extended period of time, you could also track the sessions via the DB and not in memory.
Also, if you are worried about the indefinite open session, you could implement a timeout from when the session opened and if there is an extended idle time.

Is there an alternative of ajax that does not require polling without server side modifications?

I'm trying to create a small and basic "ajax" based multiplayer game. Coordinates of objects are being given by a PHP "handler". This handler.php file is being polled every 200MS, by using ajax.
Since there is no need to poll when nothing happens, I wonder, is there something that could do the same thing without frequent polling? Eg. Comet, though I heard that you need to configure server side applications for Comet. It's a shared webserver, so I can't do that.
Maybe prevent the handler.php file from even returning a response if nothing has to be changed at the client, is that possible? Then again you'd still have the client uselessly asking for a response even though something hasn't changed yet. Basically, it should only use bandwidth and sever resources if something needs to be told to the client, eg. the change of an object's coordinates.
Comet is generally used for this kind of thing, and it can be a fragile setup as it's not a particularly common technology so it can be easy not to "get it right." That said, there are more resources available now than when I last tried it ~2 years ago.
I don't think you can do what you're thinking and have handler.php simply not return anything and stop execution: The web server will keep the connection open and prevent any further polling until handler.php does something (terminates or provides output). When it does, you're still handling a response.
You can try a long polling technique, where your AJAX allows a very large timeout (e.g. 30 seconds), and handler.php spins without responding until it has something to report, then returns. (You'll want to make sure the spinning is not resource-intensive). If handler.php "expires" and nothing happens, have it exit and let AJAX poll again. Since it only happens every 30 seconds, it will be a huge improvement over ~5 times a second. That would keep your polling to a minimum.
But that's the sort of thing Comet is designed for.
As Ajax only offers you a client server request model (normally termed pull, rather than push), the only way to get data from the server is via requests. However a common technique to get around this is for the server to only respond when it has new data. So the client makes a request, the server hangs on to that request until something happens and then replies. This gets around the need for frequent polling even when the data hasn't changed as you only need the client send a new request after it gets a response.
Since you are using PHP, one simple method might be to have the PHP code call the sleep command for 200ms at a time between checks for data changes and then return the data to the client when it does change.
EDIT: I would also recommend having a timeout on the request. So if nothing happens for say 2 seconds, a "no change" message is sent back. That way the client knows the server is still alive and processing its request.
Since this is tagged “html5”: HTML5 has <eventsource> and WebSocket, but the implementation side is still in the future tense in practice.
Opera implemented an old version of <eventsource> called <event-source>.
Here's a solution - use a SaaS comet provider, such as WebSync On-Demand. No server resources to worry about, shared hosting or not, since it's all offloaded, and you can push out the information as needed.
Since it's SaaS, it'll work with any server language. For PHP, there's already a publisher written and ready to go.
The server must take part in this. Check with the hosting provider what modules are available. Or try to convince them to support Comet.
Maybe you should consider a small Virtual Private Server (VPS) for this.
One thing to add on the long polling suggestions: If you're on a shared server, this solution will have limited scalability, as each active long poll will keep a connection (and a server-side process to service that connection) active. Your provider most likely has limits (either policy-defined or de facto) on the number of connections you can have open at a time, so you'll hit a wall if you have more sessions/windows than that playing concurrently.

How do deal with OpenX XMLRPC authentication / sessions

I am having trouble with Openx; here is the issue
OpenX::Services::Base.connection returns the class variable ##connection which is populated by OpenX::Services::Base.connection if it has previously not been initialized.
The problem with it being a class variable is that it persists across connections, which means if there is a lull in activity, the XMLRPC session between my site and OpenX will time out, and the OpenX API has no provisions for communicating an expired session, which would be wasteful anyways as it would require a request before every communication just to verify that the session was still valid.
What I think would be a better way to do it would be to instantiate a connection at the beginning of any request that needs OpenX support, and to close it at the end, ensuring that there is no possibility of a session time-out on the XMLRPC side of things.
Has anyone else encounted this when using OpenX / OpenX XMLRPC? If so how did you resolve this issue?
I have a try/catch block around the OpenX RPC call, and I wrote an exception translator. If I detect a session timeout I will execute a again the login operation, I will take the new session id and I will run the failed OpenX call again. It is a little bit more complicated than having a cron job in order to keep the session alive but more performant and robust (in my opinion).
We faced the same issue. Our solution: Create a unauthenticated controller which does some simple interactions with the OpenX API (just to keep it live) and have this URL invoked by a cron job every 5-10 min.
What solution did you use?

Resources