I am creating a login authentication system using password_hash and password_verify in PHP.
Can't implement well.
Password can be registered in MySQL using password_hash ($user_pass, PASSWORD_DEFAULT).
However, I can't figure out how to use password_verify to create a function that checks whether the passwords match.
If i try login authentication with the following code, the user ID or password is incorrect. It will be displayed.
It ’s a situation where you do n’t even know what ’s wrong.
Thank you for pointing out the improvements.

Error message

No error message.

Applicable source code
try {
  $user_id = $_POST ['id'];
  $user_pass = $_POST ['pass'];
  $user_id = htmlspecialchars ($user_id, ENT_QUOTES, 'UTF-8');
  $user_pass = htmlspecialchars ($user_pass, ENT_QUOTES, 'UTF-8');
  $dsn = 'mysql: dbname = sample;host = localhost;charset = utf8';
  $user = 'root';
  $password = '';
  $dbh = new PDO ($dsn, $user, $password);
  $dbh->setAttribute (PDO :: ATTR_ERRMODE, PDO :: ERRMODE_EXCEPTION);
  $sql = 'SELECT password FROM sample WHERE id =?';
  $data [] = $user_id;
  $stmt = $dbh->prepare ($sql);
  $rec = $stmt->fetch (PDO :: FETCH_ASSOC);
  if (! empty ($rec)&&password_verify ($user_pass, array_shift ($rec))) {
    User ID and password match.<br/>;
  } else {
  print 'The user ID or password is incorrect.<br/>';
    exit ();
  catch (Exeption $e) {
    exit ();
Source code

I actually entered my ID and password and executed it.
The user ID or password is incorrect. It will be out.

  • Answer # 1

    Isn't it because the prepared statement doesn't apply the key id?

  • Answer # 2

    Look at the password_verify manual first.

    Please understand the return value.

    $user_pass = password_verify ($user_pass, $result)
      $sql = 'SELECT username, password FROM sample WHERE id =? AND password =?';
      $stmt = $dbh->prepare ($sql);
      $data [] = $user_id;
      $data [] = $user_pass;

    I think the above code is for not understanding the contents of the process.