Destroy Session when changing profile on mobile and affect pc

Asked

Viewed 90 times

-2

Hello,

How do I solve the problem when someone edit the profile on mobile and at the same time is logged in on the pc, do not give php error as 'Undefined variable' on the pc because the data is no longer the same as mobile..

For example, the login is William ai I logged in on mobile and pc, then I edited my login on mobile to curruwilla and saved, ai on pc is like William still giving error

Here ta as Session to retrieve user data: How can I improve this to select the users by ID for when I do not change the username or password does not give error ?

if(isset($_SESSION['useronnected']) && (isset($_SESSION['passconnected']))){
$userLogged = $_SESSION['useronnected'];
$passLogged = $_SESSION['passconnected'];

// seleciona o usuario logado
    $selectLogged = "SELECT * from users WHERE user=:userLogged AND password=:passLogged";
    try {
        $result = $conexao->prepare($selectLogged);
        $result->bindParam('userLogged', $userLogged, PDO::PARAM_STR);
        $result->bindParam('passLogged', $passLogged, PDO::PARAM_STR);
        $result->execute();
        $count = $result->rowCount();

        if($count =1){
            $loop = $result->fetchAll();
            foreach ($loop as $show) {
                $idLogged = $show['id'];
                $nameLogged = $show['name'];
                $userLogged = $show['user'];
                $passwordLogged = $show['password'];
                $emailLogged = $show['email'];
                $levelLogged = $show['level'];
            }
        }
    }catch (PDOException $e){ echo $e;}
}

if(!isset($_SESSION['useronnected']) && (!isset($_SESSION['passconnected']))){
    $levelLogged = 0;
}

And here is the login:

if(isset($_POST['loggin'])){
    // RECUPERAR DADOS DO FORM
    $user        = trim(strip_tags($_POST['user']));
    $password    = trim(strip_tags($_POST['password']));

    //SELECIONAR BANCO DE DADOS
    $select = "SELECT * FROM users WHERE BINARY user=:user AND BINARY password=:password";

    try {
        $result = $conexao->prepare($select);
        $result->bindParam(':user', $user, PDO::PARAM_STR);
        $result->bindParam(':password', $password, PDO::PARAM_STR);
        $result->execute();
        $count = $result->rowCount();

        if($count>0){
            $user    = $_POST['user'];
            $password = $_POST['password'];
            $_SESSION['useronnected'] = $user;
            $_SESSION['passconnected'] = $password;
            header("Location: page.php");
        }else{
            echo '<div class="alert alert-danger">
            <strong>Erro ao logar!</strong> Os dados estão incorretos.
            </div>';
        }
    }catch(PDOException $e){
        echo $e;
    }
}

2 answers

1


Follow a refactoring of the code, and below an explanation of the changes and their reasons:

$levelLogged = 0;
if( isset($_SESSION['userId'] ) {
    $query = 'SELECT * from users WHERE id=:userId';
    try {
        $result = $conexao->prepare( $query );
        $result->bindParam( 'userId', $userId, PDO::PARAM_STR );
        $result->execute();
        if( $result->rowCount() == 1 ){
            $dados = $result->fetch( PDO::FETCH_ASSOC );
            $nameLogged  = $dados ['name'];
            $userLogged  = $dados ['user'];
            $levelLogged = $dados ['level'];
        }
    } catch (PDOException $e){ echo $e;}
}
  • we passed the $levelLogged up, because if anything doesn’t work in query to DB, we already guarantee that the user will not have privileges on the page.

  • we exchange the verification by user id, as thus we work regardless of the name of this, other data is recovered from BD.

  • No need to fetchAll nor loop, because we are only recovering one data line.

But note: this should only be done on the pages where the data actually serve in the request body, otherwise just use the name and Id.

For the login to work with the code above, follow the refactoring of the 2nd block you posted:

if(isset($_POST['loggin'])){
    $user        = trim( $_POST['user'] );
    $password    = trim( $_POST['password'] );

    $select = "SELECT * FROM users WHERE user=:user AND BINARY password=:password";

    try {
        $result = $conexao->prepare($select);
        $result->bindParam(':user', $user, PDO::PARAM_STR);
        $result->bindParam(':password', $password, PDO::PARAM_STR);
        $result->execute();
        $count = $result->rowCount();

        if( $count == 1 ){ [userId'] = $user;
            $dados = $result->fetch( PDO::FETCH_ASSOC );
            $_SESSION['userId']    = $dados['name'];
            $_SESSION['userName']  = $dados['name'];
            $_SESSION['userLevel'] = $dados['level'];
            header("Location: page.php");
            die();
        }else{
            $_SESSION['userId']     = 0;
            $_SESSION['userName']   = '';
            $_SESSION['userLevel']  = 0;

            echo '<div class="alert alert-danger">
            <strong>Erro ao logar!</strong> Os dados estão incorretos.
            </div>';
        }
    }catch(PDOException $e){
        echo $e;
    }
}

Here we change the following:

  • We add the userId in Session, which is the basis of the user’s identity. In fact, the field’s ID name comes from identity, which is the concept of immutable information. The user can change name, sex, address, but in theory the Id will always be the same.

  • the userLevel and the userName are already caught and stored in the Session, instead of requiring DB on all pages. Thus, the first block you posted will only be needed in more complex operations, which depend on this updated data. In other parts, just use the Session. In a name change, the open session will be left with the old name until it closes.

  • we changed the Count test to == 1, because if there is more than 1 user with the same credentials in DB, something is wrong.

  • if the transaction is unsuccessful, we are resetting the data from the Session "in the bush".

  • important that we use the die() after redirect header, (or exit()), because without it, the user receives the data from the page, and only then is redirected. Normally we don’t see this because the redirect is fast, but nothing guarantees that it will happen or that the information will not be interpreted before the redirect.

  • the BINARY of the username has been removed, as usually uppercase and lowercase are important only in the password. This is just to show as an alternative, but you must adapt to what you think is correct in your system.

Insisting on the observation made previously: using the 2nd block of the way we did (adjusting for your real case, of course), we do not need to search the DB with the 1st block at all times, because the Session will already have the fundamental data. Understanding this concept, you will know when it is time to review the DB, and when you can use the session data.

  • @William your question was reopened by the community, so I posted a summary of what I had already answered in the comments. If that’s the case, then I’ll add a little extra detail to it. The comments I keep erasing later, not to be too messy in the question.

-1

If you write user data in session, this problem will happen every time you open more than one session to the same user (be it PC+mobile, be PC+PC, etc).

To solve this, there are three ways.

1) You record it only the user ID in the session and requests the other data to the database in all your requests.

2nd) You create a button to UPDATE data to bring new database data.

3rd) You use socket communication to update real team (instant). This way will give you more work, but it will also open up new paths. Search for Ratchet to implement it.

  • 1

    I would like the honourable Members to comment on the vote against, so that I can improve my knowledge or correct any possible poorly explained text.

  • Okay, Bacco, thank you so much for the tip. How would you solve this problem? Can you help us?

  • If it’s something I understand, I can try to help. How would I solve what problem, what I commented on before, or the author of the question? In the second case, I posted some recommendations, which I had commented to him. In the first case, I do not know if any of the things I had commented could be the reason for any negative (but I posted after the answer was already negative, and the score did not change after that) Edit: the author’s own question was with -4, but after he gave an elaborate already had 2 positive. In score it pays, because each positive is worth 10, each negative costs only 2.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.