First of all, I recommend reading this question:
How to hash passwords securely?
Here are two examples of password_hash
using mysqli
and bind_param
, dispensing with the need to do any kind of escape manually.
The bind param
already automatically escapes the values:
Example password storage with password_hash:
$mysqli = new mysqli( 'enderecodoservidor', 'usuario', 'senha', 'basededados' );
$usuario = $_POST['usuario'];
$hash = password_hash( $_POST['senha'], PASSWORD_DEFAULT );
$query = 'INSERT INTO usuarios ( nome, hash) VALUES ( ?, ? )';
$stmt = $mysqli->prepare( $query );
$stmt->bind_param("ss", $usuario, $hash );
$stmt->execute();
Example password update with password_hash:
$mysqli = new mysqli( 'enderecodoservidor', 'usuario', 'senha', 'basededados' );
$usuario = $_session['usuario']; // ou idusuario, depende como voce mantem o login
$hash = password_hash( $_POST['novaSenha'], PASSWORD_DEFAULT );
$query = 'UPDATE usuarios SET hash= ? WHERE nome = ? '; // ou WHERE id = ?
$stmt = $mysqli->prepare( $query );
$stmt->bind_param("ss", $hash , $usuario ); // ou ("si", $hash, $idUsuario)
$stmt->execute();
Example password verification with password_hash:
$mysqli = new mysqli( 'enderecodoservidor', 'usuario', 'senha', 'basededados' );
$usuario = $_POST['usuario'];
$idUsuario = 0; // Isso se trabalhar com ID numérico, o que pode ser interessante
$query = 'SELECT id, hash FROM usuarios WHERE nome = ?';
$stmt = $mysqli->prepare( $query );
$stmt->bind_param("s", $usuario );
$stmt->execute();
$stmt->bind_result( $idUsuario, $hash ); // aqui tem que bater com os campos do select
$stmt->fetch();
if ( password_verify( $_POST['senha'], $hash ) ) {
echo 'Logado';
} else {
echo 'Usuario e/ou senha invalidos';
}
Leave a varchar() field wide enough for the password hash, not to run the risk of truncating the data.
See in this post how to update the hash of passwords automatically with new versions of PHP:
/a/147319/70
@Gabrielheming already correct, copy & Paste error even. Thank you for warning. It’s amazing to have stayed this long and no one noticed! And the worst thing is that in other posts I exemplified Verify
– Bacco
@Gabrielheming edited the post, I added some extra references too, with the password_needs_rehash. maybe I went through some detail. Anything just let me know that I adjust. Thank you again for the alert.
– Bacco