How to update a password in MYSQL and encrypt it

Asked

Viewed 1,507 times

1

So guys, I want to do the following, I have a site that contains users and such, but when a user wants to change his password I want it to be encrypted to BD, how can I do that? when the user is registered, his password will be encrypted to MYSQL. I will send the registration code:

<?php
session_start();
ob_start();
$btnCadUsuario = filter_input(INPUT_POST, 'btnCadUsuario', FILTER_SANITIZE_STRING);
if($btnCadUsuario){
    include_once '../Conexao/conexao.php';
    $dados_rc = filter_input_array(INPUT_POST, FILTER_DEFAULT);

    $erro = false;

    $dados_st = array_map('strip_tags', $dados_rc);
    $dados = array_map('trim', $dados_st);

    if(in_array('',$dados)){
        $erro = true;
        $_SESSION['msg'] = "<div class='alert alert-danger'>Necessário preencher todos os campos</div>";
    }elseif((strlen($dados['senha'])) < 6){
        $erro = true;
        $_SESSION['msg'] = "<div class='alert alert-danger'>A senha deve ter no mínimo 6 caracteres</div>";
    }elseif(stristr($dados['senha'], "'")) {
        $erro = true;
        $_SESSION['msg'] = "<div class='alert alert-danger'>Caracter ( ' ) utilizado na senha é inválido</div>";
    }else{ 
        $result_usuario = "SELECT idusuario FROM usuarios WHERE usuario='". $dados['usuario'] ."'";
        $resultado_usuario = mysqli_query($conn, $result_usuario);
        if(($resultado_usuario) AND ($resultado_usuario->num_rows != 0)){
            $erro = true;
            $_SESSION['msg'] = "<div class='alert alert-danger'>Este usuário já está sendo utilizado</div>";
        }

        $result_usuario = "SELECT idusuario FROM usuarios WHERE email='". $dados['email'] ."'";
        $resultado_usuario = mysqli_query($conn, $result_usuario);
        if(($resultado_usuario) AND ($resultado_usuario->num_rows != 0)){
            $erro = true;
            $_SESSION['msg'] = "<div class='alert alert-danger'>Este e-mail já está sendo utilizado</div>";
        }
    }


    //var_dump($dados);
    if(!$erro){
        //var_dump($dados);
        $dados['senha'] = password_hash($dados['senha'], PASSWORD_DEFAULT);

        $result_usuario = "INSERT INTO usuarios (nome, email, usuario, senha) VALUES (
                        '" .$dados['nome']. "',
                        '" .$dados['email']. "',
                        '" .$dados['usuario']. "',
                        '" .$dados['senha']. "'
                        )";
        $resultado_usario = mysqli_query($conn, $result_usuario);
        if(mysqli_insert_id($conn)){
            $_SESSION['msgcad'] = "<div class='alert alert-success'>Usuário cadastrado com sucesso!!</div>";
            header("Location: LoginPT-BR.php");
        }else{
            $_SESSION['msg'] = "<div class='alert alert-danger'>Error ao cadastrar usuário!!</div>";
        }
    }
}
?>

2 answers

1

Same logic as the register:

just use your encryption function password_hash(string, string) before sending:

$dados['senha'] = password_hash($dados['senha'], PASSWORD_DEFAULT);
  • When sending, "UPDATE users SET password = md5('password') Where idusuario = '$id'"; instead of going there, I put this "UPDATE users SET password = password_hash('password') Where idusuario = '$id'"; ?

  • password = password_hash('password', PASSWORD_DEFAULT)

  • It would look like this: "UPDATE usuarios SET password = password_hash('password', PASWORD_DEFAULT) Where idusuario = '$id'";, but still will not ; do this error mysqli_error() expects Exactly 1 Parameter, 0 Given in

  • "UPDATE usuarios SET password = '" . password_hash('password', PASWORD_DEFAULT). " 'Where

  • just missed to put the ' " .

  • I got a partner, like, he’s encrypting everything right now, but when I try to log in with the changed password it won’t, you know what I’m doing?

  • you checked the password in the database, saw how it turned out?

  • I checked yes friend, it was encrypted look only, the password I put was this 9934631254a then in the database was so $2y$10$2s9m6IAg2Mqb1ckZH453.uan2NuFZct4NVpeAHWdOg4lWeL67o5SG that in the case was encrypted but then when I access the account on the website not log in

  • but how do you check the login part? vc need to use the same function in password password_hash('password', PASSWORD_DEFAULT)

  • That way if(password_verify($password, $row_user['password'])){

  • change to this if your verification function does not convert the password: if(password_verify(password_hash($password, PASWORD_DEFAULT), $row_user['password'])){

  • I just changed, but now when the user creates a password for 1x the same can not enter ;\

  • Then I went back to if(password_verify($password, $row_username['password'])){ and I was able to enter, but when I change the password I can’t enter ueheu que brisa mano

Show 8 more comments

-1

You can use md5 to enter the encrypted password. An example of use would be:

  • I have the following table and want to update user password 1 to an encrypted password: inserir a descrição da imagem aqui

  • I use the command md5('password') to perform, see in practice: (with the command update tb_usuarios set dessenha = password('Kv2019@') where idusuario = 1; also works, only the type of encryption that changes, this is one more way to hash password according to the mysql reference)

update tb_usuarios set dessenha = md5('Kv2019@') where idusuario = 1;

inserir a descrição da imagem aqui

  • Now by selecting the result the password is saved encrypted:
select * from tb_usuarios;

inserir a descrição da imagem aqui

This is an example using MD5 encryption. For more read this post.

Note: I saw that you used Insert, Insert is for insertion/creation and update to update. I used the example to update only the password field, adapt to your code. Because you update password and other fields, logos the other fields also comes in the update. Ex.:

update tb_usuarios set deslogin= 'luiz.justino', dessenha = password('Kv2019@') where idusuario = 1;

That would produce: inserir a descrição da imagem aqui

In data validation you have to pass the password sent by the user to the encryption form you used. In our example how we use md5, you pass password to md5 and compare with the password md5 already recorded in the database.

Follow a function only for simple proof of access validation:

(always follow php language patterns and php documentation)

<?php



// Simulando que trazemos estas informações de um usuário que deseja acessar uma tela de login
    $id = 1;
    $login = 'luiz.justino';
    $senha = 'Kv2019@';

    $acesso = logar($login, $senha, $id);

if($acesso){
    echo "\n\n Seja bem-vindo(a) $login!";
} else {
    echo "\n\n Acesso negado!";
}

function conexaoDB(){
$conn = new mysqli('localhost', 'root', 'root', 'dbphp7', 3306);

if($conn->connect_error){
    echo "Error: " . $conn->connect_error;
}

return $conn;

}

function logar($login, $senha, $id){

    //Abre conexão com o banco
    $conn = conexaoDB();
    // Executa select para buscar informações do usuário de id = 1
    $sql = "select deslogin, dessenha from tb_usuarios where idusuario = $id";
    $result = $conn->query($sql);
    // Coloco em um array as informações de deslogin e dessenha da tabela tb_usuarios do usuário de id = 1
    $resul_dados = $result->fetch_assoc();
    // Verifico se o login e senha digitados pelos usuário são iguais as informações do banco.
    // Observe que a senha digitado pelo usuário eu tenho que passar para md5 para comparar com a senha já em md5 do banco de dados
    if ($login === $resul_dados['deslogin'] && md5($senha) === $resul_dados['dessenha']){
        // Se os dados conferem a função logar retorna TRUE
        return TRUE;
    } else {
        // Se os dados NÃO conferem a função logar retorna FALSE
        return FALSE;
    }

}


That displays the following result:

inserir a descrição da imagem aqui

  • I will test here, but in the part of INSERT is when the user will register by 1xs ó I put the code to demonstrate to you that I had put the encryption system

  • Ah understood ok. I was going to edit a reply with the update but then quiet. Abs and guy success!

  • so dude, I used this logic of yours and "worked", like, the password is encrypted and everything, but at the time of accessing the account with the password changed does not enter, I tried to put the characters that goes to the encrypted database and also did not work, my code was this "UPDATE usuarios SET password = md5('password') Where idusuario = '$id'";

  • Once you have done the update. If the user is logged in, you have to log out and access again try there.

  • I did it kkk and it doesn’t come in at all

  • Check if your comparison is like this: if (md5($senha) === $result_dados['dessenha']){&#xA; echo "\n\n Acesso liberado!";&#xA;} else {&#xA; echo "\n\n Acesso negado!";&#xA;} . The md5($senha) is the password that the user already passes the $result_dados['dessenha'] is the password I took from the database via select. Because the password that the user passes you will have to make it turn md5 to compare with the md5 that is in the bank.

  • @Luizfernando, emphasizing that it would be interesting to parameterize the query with the method prepare() and bind_param() to avoid SQL Injection problems.

  • I made it clear in my reply that I gave an example to demonstrate the function and that it should follow php’s documentation and standards. He following the documentation and standard will read about field validation and safety precautions.

Show 3 more comments

Browser other questions tagged

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