Page 1 of 1

prevent users from starting more than one session

Posted: Tue Jan 17, 2006 6:10 am
by ashosheh
hi all.
how can i prevent users from being logged in more than one time without being logged out (i.e start multisessions with the server )

note : i use PHP 4 with apache 1.3

thanx in advance

Posted: Tue Jan 17, 2006 7:01 am
by Jenk
Store the session ID with the user ID on a table, when a user starts a session, check if the old session ID that is on the table is still valid, if it is - use that ID.

Something like:

Code: Select all

<?php
session_start();

function sessioncheck ($userid, $sessid)
{
    $sql = "SELECT `sessid` FROM `users` WHERE `userid` = '$userid'";
    $result = mysql_query($sql);
    $row = mysql_fetch_assoc($result);

    if ($row['sessid'] != ($newsess = session_id())) {

        if (isset($_SESSION['initiated'])) {
            //session is already active..
            session_id($sessid); //set to existing sessid
            session_destroy($newsess);  //destroy 'new' session
        } else {
            //first time login..
            mysql_query("UPDATE `users` SET `sessid` = '" . session_id() . "' WHERE `userid` = '$userid'");
            $_SESSION['initiated'] = TRUE;
        }

    } else {
        //this is the current session.. do nothing.
    }

}
?>
Untested, but I *think* is on the right track.. may be better to break up into smaller functions, namely one to check which returns boolean and a second to update if necessary. (in an object, so you have $obj->checkSession($userid, $sessid) and $obj->setSessionID($userid, $sessid);)

Posted: Tue Jan 17, 2006 9:25 am
by raghavan20
Jenk is right, I have implemented this...I will tell you the exact logic.
Every logged in user can have only one session and this session is stored in the db record which can only be updated.
Whenever, the user sends a request for a page make sure session_id() value is same as the session id value stored in db when the user logged in to the website for the first time.

If the user logs in again, he overwrites the existing session id value, so this new session becomes valid and the older one is invalid.

IMPORTANT: Do allow only update for the session id field in the db.

Posted: Tue Jan 17, 2006 10:14 am
by John Cartwright
If the user logs in again, he overwrites the existing session id value, so this new session becomes valid and the older one is invalid.
Why not force the user log out first?

Posted: Tue Jan 17, 2006 10:23 am
by Jenk
inconvinience, people like the "Remember me" option on sites. :)