Hướng dẫn php password match

You get the weird output, because of two errors you did in your code.

1. You used password_hash[] and pasword_verify[] not in the correct way

To verify if you have the same password, you take the password from the $_POST and hash it via $passW = password_hash[$_POST['pass'], PASSWORD_DEFAULT];. You then check if this password is in your file with the command password_verify[$passW, $parts[1]]. The correct way anyway is, that you use password_hash[] when you save the password and only then. If you want to check if the password was saved you use password_verify[] with the unhashed password:

$passW = $_POST['pass'];
....
if [$userN==$parts[0] && password_verify[$passW, $parts[1]]] {
...

Like this the check will work.

2. You echo the output of your login for each iteration in your loop

You get the text "Wrong username/password!" three times on each login try. This is because the line echo "Wrong username/password!"; is inside of your foreach loop and your file contains three lines. Instead, you should not use the else block of your condition to handle the output of a wrong login attempt, because you leave the page in case of a successful login anway. So you can safely add a die[] after the redirection to stop further code execution and print out the error message in any other way. Because the check $userN === $parts[0] is also part of that check it was executed for each row anyway, which resulted in a wrong output.

foreach[$userList as $row] { 
    $parts = explode[";",$row];
    if[$userN === $parts[0] && password_verify[$passW, $parts[1]]] {
        $_SESSION['username'] = $_POST['namn'];
        header["Location:index.php"];
        die[];
    }
}
echo "Wrong username/password!";

Because of the die[] command the error message will only be printed if the login was not successful. Because it is outside of the foreach loop it will be printed only once.

Cập nhật ngày 27/12/2021

Trong PHP, muốn sử dụng mã hoá Bcrypt ta sẽ dùng hàm password_hash[]. Hàm này thường dùng để mã hoá mật khẩu.

Ngoài mã hoá Bcrypt hàm này còn hỗ trợ mã hoá Argon2i và Argon2id.

password_hash [ string $password , int $algo [, array $options ] ] : string

Trong đó:

  • $password: chuỗi cần mã hoá
  • $algo: Phương thức mã hoá [mặc định là Bcrypt]. [xem thêm]
  • $options: mảng tùy chọn [xem thêm]

Kết quả:

Trả về chuỗi mã hoá hoặc FALSE nếu thất bại.

Ví dụ:

Chủ Đề