PHP password_verify
Summary: in this tutorial, you’ll learn to use the PHP password_verify() function to check if a password matches a hashed password.
Introduction to the PHP password_verify() function
When dealing with passwords, you should never store them in the database as plain text. And you should always hash the passwords using a secure one-way hash algorithm.
PHP provided the built-in password_hash() function that creates a hash from a plain text password. Note that the password_hash() function is a one-way hash function. It means that you cannot find its original value.
To verify if a plain text password matches a hashed password, you must hash the plain text password and compare the hashes.
However, you don’t have to do it manually since PHP provides you with the built-in password_verify() function that allows you to compare a password with a hash:
password_verify(string $password, string $hash): bool
Code language: PHP (php)
The password_verify() has two parameters:
- $password is a plain text password to match.
- $hash is a hash created by the password_hash() function.
The password_verify() function returns true if the password matches the hash or false otherwise.
PHP password_verify() function example
The following example uses the password_verify() function to check if the password Password1 matches a hash:
$hash = '$2y$10$hnQY9vdyZUcwzg2CO7ykf.a4iI5ij4Pi5ZwySwplFJM7AKUNUVssO'; $valid = password_verify('Password1', $hash); echo $valid ? 'Valid' : 'Not valid';
Code language: PHP (php)
Valid
Code language: PHP (php)
In practice, you’ll use the password_verify() function as following to verify a login:
- Find a user from the database by a username (or email)
- Use the password_verify() function to match the user’s provided password with a hashed password.
- If the password matches the hash, you log the user in. Otherwise, you’ll issue an error message.
The code will look like the following:
// . $user = find_user_by_username($username); if ($user && password_verify($password, $user['password'])) < // log the user in session_regenerate_id(); $_SESSION['user_id'] = $user['id']; > else < echo 'Invalid username or password'; >
Code language: PHP (php)
In the following tutorial, you’ll learn to use the password_verify() function in the login form.
Summary
- Use the PHP password_verify() function to check if a password matches a hashed password created by the password_hash() function.
Авторизация на PHP — как вывести сообщение б ошибке в самой форме?
Подскажите пожалуйста, как ввести в само форме сообщение об ошибке если пользователь существует в базе, длина пароля больше заданного значения и т.д.?
Ошибка формируется в переменную $error = »;
Раньше выврдилось через die();
Но сейчас у меня проблема втом, что мне приходится дублировать форму два раза, чтобы вывести сообщения об ошибке. Как можно оставить одну форму и вывести в ней все ошибки?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
//Если пришли данные на обработку if(isset($_POST['login']) && isset($_POST['password'])) { //Записываем все в переменные $login=htmlspecialchars(trim($_POST['login'])); $password=htmlspecialchars(trim($_POST['password'])); $mdPassword = md5($password); // Подключение к базе данных require_once 'db_connect.php'; //Достаем из таблицы инфу о пользователе по логину $res=mysql_query("SELECT * FROM `users` WHERE `login`='$login' "); $data=mysql_fetch_array($res); //Если такого нет, то пишем что нет if(empty($data['login'])) { require_once 'header.php'; $error = 'Такого пользователя не существует!'; } else { //Если пароли не совпадают if($mdPassword!=$data['password']) { require_once 'header.php'; $error = 'Введенный пароль неверен!'; } else { //Если капча не совпадают if($_POST['kapcha'] != $_SESSION['rand_code']) { require_once 'header.php'; $error = 'Капча введена неверно'; } } } ?>