Using sessions is a good way to do this, and is a very common method for controlling authentication.
The flow usually looks something like this:
- User visits site, and session_start() is called. A unique session identifier is set for that visitor (ie. a cookie).
- User submits his login credentials to a login form
- Login credentials are verified, and this fact is stored in the session data with
$_SESSION['logged_in'] = true
, or something similar
- For the rest of the user's time on the site, you can check
$_SESSION['logged_in']
to see if the user has logged in.
In order to control a user's logins, you could simply have a field in a database (users
table is fine) indicating what the current session id is (retrieved with session_id()
) for the user, and if it doesn't match the cookie value you just received, then you immediately call session_destroy()
for that id, and consider the user as logged out.
Using $_SESSION
means you don't have to worry about generating your own tokens, and gives you the power of the built-in superglobals to facilitate storing information about the user's authentication status.
Personally, I would allow multiple sessions to be active for a user for most web sites, as there's usually not a good reason not to, but it obviously depends on the nature of the site. However, storing the current active session id as mentioned above is a pretty simple way to accomplish this.