php - check if the user with email X has 1 or 2 sessions open

2

Good,

I'd like to know the safest and simplest way to check if a user is connected 2x in the same email. If it is, it simply cancels 1 and gets the other one.

How can I enhance this verification?

    
asked by anonymous 08.07.2018 / 19:20

1 answer

0

There are several ways to do this. One option is to create a hashed value that is saved in the database for later verification. For example:

After the user confirms the email and password you open a session:

session_start();

$email = '[email protected]';

// esse é o valor gerado no após a confirmação do usuário
$valor_da_sessao = crypt($email, md5(date("d/m/Y H:i:s")));

$_SESSION['user'] = $valor_da_sessao;

// salva a sessao no banco de dados

$query = mysqli_query($conexao, "UPDATE sessao SET valor = '$valor_da_sessao' WHERE email = '$email'");

if($query){
    echo "DEU CERTO!";
    header("Location: pagina_inicial.php");
} else {
    echo "DEU ERRADO!"
}

Now, you only have to check, with each user action, if the session used by him is the original session.

So:

session_start();

$valor_da_sessao = $_SESSION['user'];

$query = mysqli_query($conexao, "SELECT * FROM sessao WHERE valor = '$valor_da_sessao'");

if(mysqli_num_rows($query) == 0){
    /*

        ESSA SESSÃO NÃO É ORIGINAL

    */

    unset($_SESSION['user']);
    session_destroy();
}

EDIT

After some comments from @Inkeliz, I was shown that it really is easy to circumvent the answer above. But it is easy to be corrected too! To do this, you need to change the session value and the bank value for each user action. It will be impossible, in this way, the same user to be in 2 places at the same time.

So:

session_start();

$email = '[email protected]';

if(isset($_SESSION['user'])){

    $valor_da_sessao = $_SESSION['user'];

    $query = mysqli_query($conexao, "SELECT * FROM sessao WHERE valor = '$valor_da_sessao'");

    if(mysqli_num_rows($query) == 0){

        /*

            ESSA SESSÃO NÃO É ORIGINAL

        */

        unset($_SESSION['user']);
        session_destroy();

    } else {

        /*

            ESSA SESSÃO É ORIGINAL
            CRIA UM NOVO VALOR
            SALVA NO BANCO

        */

        $valor_da_sessao = crypt($email, md5(date("d/m/Y H:i:s")));

        $_SESSION['user'] = $valor_da_sessao;

        mysqli_query($conexao, "UPDATE sessao SET valor = '$valor_da_sessao' WHERE email = '$email'");

    }

}
    
08.07.2018 / 22:10