-1

typically you would write a sql statement in php like so, to query mysql database.

$sql="select * from table where userid='username' and password='$pass'";

My question is, if i'm using password_hash($pass,PASSWORD_BCRYPT) to encrypt my password, how do i write the above query to retrieve some rows from my database, since the hashed password stored in the database will not be the same text password input by the user? Pls advice. Thanks.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
schenker
  • 941
  • 3
  • 12
  • 25

1 Answers1

0

For storing password into database

<?php
/**
 * Note that the salt here is randomly generated.
 * Never use a static salt or one that is not randomly generated.
 *
 * For the VAST majority of use-cases, let password_hash generate the salt randomly for you
 */
$options = [
    'cost' => 11,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."\n";
?>

IF you want to verify password using password_verify() function.

First, fetch stored hashed password from the database, then use the password_verify() function

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$11$lBi3B5rakkB6CBJRLn2e6O1RppUr2y5r0W/4Z0jJBGqE9cdYK.1sa';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

?>

Click HERE TO CHECK

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Siddhartha esunuri
  • 1,104
  • 1
  • 17
  • 29
  • 1
    `echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."\n";` - The `."\n"` needs to be removed here. That will store a hidden line break in the hash, making it impossible to use `password_verify()`. The manual http://php.net/manual/en/function.password-hash.php has been updated since. – Funk Forty Niner Jan 13 '19 at 17:36