Avoid double login

2

I'm having a problem with double logging. I want that, when a user is logged into a browser and wants to log in with the same account in another browser, this one does not allow it.

How can I do it in PHP?

This is my session code:

$user_ip = $_SERVER['REMOTE_ADDR'];
$username = isset($_POST['usuario']) ? addslashes(trim($_POST['usuario'])) : '';
$password = isset($_POST['contrasenia']) ? addslashes(trim($_POST['contrasenia'])) : '';
$errors = array();
if(isset($_POST) && !empty($_POST)){
    // Validar nombre de usuario.
    $query = @mssql_query('SELECT UserID,Pw FROM  PS_UserData.dbo.Users_Master WHERE UserID = \'' . $username . '\'');
    if(empty($username)){
        $errors[] = 'Por favor, proporcione un nombre de usuario.';
    }else if(strlen($username) < 3 || strlen($username) > 16){
        $errors[] = 'Nombre de usuario debe tener entre 3 y 16 caracteres de longitud.';
    }else if(ctype_alnum($username) === false){
        //$errors[] = '';//Nombre de usuario debe consistir en números y letras únicamente.;
    }else if (mssql_num_rows($query) == 0){
        $errors[] = 'el usuario no existe';
    }
    // Validar la contraseña de usuario.
    $query2 = @mssql_query('SELECT UserID,Pw FROM  PS_UserData.dbo.Users_Master WHERE UserID = \'' . $username . '\' and PW = \'' . $password . '\'');
    if(empty($password)){
        $errors[] = 'Por favor ingrese su contraseña.';
    }else if(strlen($password) < 3 || strlen($password) > 16){
        $errors[] = 'La contraseña debe tener entre 3 y 16 caracteres de longitud.';
    }else if (mssql_num_rows($query2) == 0){
        $errors[] = 'Por favor, proporcione la contraseña correcta.';
    }
    
asked by Jhoni Williands 14.10.2016 в 09:42
source

5 answers

2

Since everyone is using the answers to write opinions without code ... I will not be less, but I will provide code.

What I recommend is that you do not block a new attempt to log in, that will generate more problems than advantages. Focus on discarding the old session and allowing the new one.

How? The simplest thing is to reuse the user table and add a "SID" field in which you will store the SID of the session you signed in.

NOTE: I'm going to use PDO, remember that the mssql_* functions are outdated and insecure.

After logging in and setting $_SESSION['UserID'] to the appropriate value you save the value of SID in the user table in the field you created for that function:

<?php
$consulta = $pdo->prepare('
  UPDATE PS_UserData.dbo.Users_Master
    SET SID = :SID
    WHERE UserID = :UserID
');
$consulta->execute([
  ':UserID' => $_SESSION['UserID'],
  ':ID' => SID,
]);

Now, just after establishing the connection to the database and performing the security checks you have implemented (access levels, etc) you should check that the SID matches:

<?php
$consulta = $pdo->prepare('
  SELECT SID
    FROM PS_UserData.dbo.Users_Master
    WHERE UserID = :UserID
');
$consulta->execute([
  ':UserID' => $_SESSION['UserID'],
]);
$resultado = $consulta->fetch(PDO::FETCH_ASSOC);
if ($resultado === FALSE) {
  die('Error: ¿¿Usuario no existente??');
}
if ($resultado['SID'] !== SID) {
  /* ¡Es una sesión antigua! Han iniciado sesión en otro equipo,
    invalidamos la información de la sesión actual y reenviamos
    al usuario a la página de entrada */
  unset($_SESSION);
  session_destroy();
  /* Opcionalmente podemos destruir la cookie de sesión */
  header('Location: entrada.php');
  exit();
}
/* A partir de aquí todo va bien, el usuario tiene únicamente
  una sesión activa */

I hope it helps you.

    
answered by 14.10.2016 в 22:28
0

You must create a column in the user table where every time you log in the session id is stored, and every time a request is made it must be verified that the session id matches the stored one otherwise it will be closed the session

    
answered by 14.10.2016 в 16:10
0

Another solution is to use the

  

localStorage

of the browser, using Javascript, to store the session id of the user, if this does not exist in the browser, it will mean that it must be registered again.

    
answered by 14.10.2016 в 16:14
0

A new table in which you save when a user starts and closes the session. When trying to connect to a new browser and if it already has a session started it is rejected. But there will be a problem when you know when "really" finished the current session.

    
answered by 14.10.2016 в 16:22
0

I hope this serves you, what works for me is to create a field in the database that is updated to 1 when the user logs in and updates to 0 when logging out

This way when you run the function login verify that this field is at 0 and if so continue with the login and update it to 1, using this when you want to log in to another browser you will find that the field has 1 and it will not continue, the problem that I had was with the default time of the cookie or the session because if this is the case when the session is closed it will not update the table to 0 and you will not be able to log in again.

To solve it use persistent sessions and the cookie that expires in a long time

Example:

Database:

  • id | 1
  • username | test
  • password | 12345
  • loggedin | 0 // when registering the user this must be 0 by default, this is achieved using 'default' when creating the field in the base of data

Now we have to obtain the value of that field using a query. Suppose that the variable assigned to that field after the query is $ loggedin

Within the login function, only one IF is required:

if ($loggedin == 0){
  // Continuar con la funcion login y usar un 'UPDATE' para cambiar el valor de 0 a 1

}else{
 // redireccionar a index
}

At the moment of closing session you have to also make an 'UPDATE' to change the value from 1 to 0

To avoid that the session expires and you can never access again you can review these publications:

Persistent sessions Cookie never expires

I hope it works for you Greetings

    
answered by 14.10.2016 в 21:52