I am trying to create a login system using PHP and MySQL. I am using cookies in order to keep the users logged in for a long period of time. The cookie has a randomly-generated string, which is also in the database. They are compared to each other and appropriate action is taken. Basically, it’s the standard authentication system.
My problem is that I am not quite sure on how to approach the problem of authentication from multiple locations. As there is only one random string for each user, he will be logged out from one location if he logs in from another.
The only solution I can come up with is a table in which the multiple logins of the user are stored, each with a separate random string in it.
Is this the right way to go? What happens with the unused sessions?
If you want to support multiple locations, you can’t keep the cookie values in your user table. Rather you should create a new autologins table, using the cookie values and user id as the primary and foreign key respectively. I believe that was your idea as well.
Then, for housekeeping purposes, you can record the last time any value was last used to login. Anything over XX days gets removed and the user need to sign in again. You can either set up a cron job for that or have it run every time someone signs in with a cookie.
A cron removal job can process more records (because nobody is waiting for it to complete), but for optimization you need an index on the date field (to prevent a table scan).
Housekeeping at every login has the advantage that you only have to query the cookie values for that user and thanks to the foreign key constraint the lookup is fast. But you can only clean up the current user’s cookies, so you may collect cookies that are never used again.