Destroy session when changing profile on mobile and affect pc

-2

Hello,

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

For example, the login is william ai I logged in the cell phone and the pc, then I edited my cell phone login to curruwilla and I saved it, there on the pc it is like william still giving error

Here is a session to retrieve user data: How can I improve this to select users by ID for when I do not change the username or password do 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's your 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;
    }
}
    
asked by anonymous 14.12.2015 / 22:20

2 answers

1

Here is 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 have passed the $ levelLogged up, because if anything does not work in DB, we already guarantee that the user will not have privileges on the page.

  • >
  • We changed the check by the user id, because we worked independently of the user name, the other data is retrieved from the database.

  • There is no need for fetchAll and loop , as we are only retrieving one row of data.

But note: this should only be done on the pages where the data is actually serving in the request body, otherwise just use the name and ID

In order for the login to work with the above code, follow the 2nd block refactoring 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 added userId to the session, which is the basis of the user's identity. In fact, the name ID of the field comes from identity, which is the concept of immutable information. The user can change name, gender, address, but in theory the Id will always be the same.

  • userLevel and userName are already taken and saved in session instead of requiring DB request on all pages. So the first block you posted will only be needed on more complex operations that depend on this updated data. Elsewhere, just use session . In a name change, the open session will remain with the old name until closing.

  • We changed the count test to == 1 , because if you have more than 1 user with the same credentials in the DB, something is wrong.

  • If the transaction is unsuccessful, we are zeroing the session data.

  • We use die() after redirect header, (or exit() ), because without it, the user receives the data from the page, and then is redirected. Normally we do not 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.

  • BINARY has been removed from the username, because it is usually case sensitive only in the password. This is just to show you as an alternative, but you should match what you think is right for 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, since the session will already have the key data. Understanding this concept, you will know when it is time to revise the DB, and when you can use session data.

    
15.12.2015 / 02:05
-1

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

To solve this, there are three ways.

1st) You only record the user ID in the session and request the other data to the bank in all your requests.

2nd) You create a button to UPDATE data to bring the new data from the bank.

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

    
14.12.2015 / 22:39