• Prevent Multiple Concurrent sessions in PHP

    If one user is logged in with his/her details from one IP and another user is trying to login with the same details from the IP, it should not allow this.

    Let’s get started:

    Step 1 : Create table in MYSQL database as mention below

    View Code DATABASE
    1
    2
    3
    4
    5
    
    CREATE TABLE `sessions` (
    `user_id` INT( 11 ) NOT NULL ,
    `session_id` VARCHAR( 32 ) NOT NULL ,
    `created` TIMESTAMP( 14 ) NOT NULL
    ) ENGINE = MYISAM ;

    Step 2 : Put the below code at that place where you have put the login code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    <?
    #Prevent Membership Fraud
    //check if someone is logged in
    if (isset($_SESSION['user_id'])) {
    //connect to your db
    require('connect.php');// Include file for database connection
    /*build query using hirer_id and current_session_id, get count. If query comes back with a 1, it means there is a match. A match is good because it means no one else logged in during their session. On the other hand, a 0 indicates that no match, meaning someone else logged in simultaneously. Zeros get the boot of death.*/
    $result = mysql_query('SELECT COUNT(*) FROM user WHERE user_id='.$_SESSION['user_id']." AND session_id='".mysql_real_escape_string(md5(session_id()))."'");
    $login_status = mysql_result($result,0,0);
    //recall 1 is good, 0 is bad
    if (0 == $login_status) {
    //give them the boot
    //this is copied from my logout script
    $_SESSION = array(); //destroy the variables
    session_destroy(); //destroy the session itself
    setcookie(session_name(), '', time()-300, '/', '', 0); //destroy the cookie
    echo 'Hey, someone else logged in using your account info.';
    exit();
    }
    }
     
    ?>

Comments on this post

Leave a Reply

  • Security Code :


    − 7 = one