Maintaining a single logged user into an account in php
I want to make a login system using PHP and MySQL and do it in such a way that every-time only one person is logged into my system at any point 开发者_JS百科of time. If the same user logs in on another window/session/place the old running instance should be invalidated and the new one should be validated.
I am aware that I can get this done by storing the session-id in the database and some routine that checks it and keeps on verifying it constantly periodically or on any database action.
Is there any other way I can accomplish this so that the checks for verification are minimized and I don't have to fire a query on each page refresh to check if the user is in the last logged valid login session.
In short I can summarize that i need a technique so that only my last valid login browser window is served the webapp.
You don't need to have any polling method, in fact you all you need to do is store the session id of any logged in user along with their username in a database.
Then, on each login, simply check if the user logging in already has a stored session. If they do, invalidate that one and store the newly logged in session in a database.
When an old session tries to reconnect to the app, the data for their session will no longer be stored on your server, so they won't be logged in any longer.
All this requires is making an extra check anytime somebody logs in, not any polling method or the like.
Every time the user loads a site of your homepage you have to check whether the user is logged in or not. This is always one sql query. So store the session-key along with the user-data and than you can simply add the session-key to the WHERE-clause to identify the user. In this way you have only your one sql query which you have anyway to verfiy that the user is logged in.
Firstly, I'd build this with a database to manage your session policy. If it turns out to be bottleneck, you can optimise then.
If the application runs on a single server, you could perhaps use shared memory (e.g. using APC's apc_store & apc_fetch) to store some state information which can be shared among processes. This could simply store the last-known session id, keyed on the user id. Then you can quickly discover if the current session is still valid.
If you're running on multiple servers, then memcache might be worth a look for achieving something similar.
精彩评论