我正在学习PHP的哈希和salting函数,并希望尝试一下,所以我在phpmyadmin中创建了一个本地数据库和表,其中包含两列(用户名和密码),并用一个用户名和哈希密码填充它。登记/> 现在我想知道,有没有更好的方法来做我做过的事情,或者我不应该做的事情? (我知道有特定的错误消息很糟糕,这只是出于测试目的。)
数据库:db_users
表:用户
用户名:用户名
密码:$ 2y $ 11 $ uJiGb3suyiupJNn9MuHNpu7dt6BwB9kS6I4fHDutknggio5PeJ17u
$DB_NAME = "db_users";
$TABLE_NAME = "users";
// The submitted values from the username and password textboxes
$username = $_POST["username"];
$password = $_POST["password"];
// Hash and salt options
$options = [
'cost' => 11,
'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
$connection = new PDO("mysql:host=localhost", "root", "password");
$sql = $connection->prepare("
SELECT username
FROM $DB_NAME.$TABLE_NAME
WHERE (username=:user);");
$sql->bindParam(":user", $username);
$sql->execute();
$rows = $sql->fetch(PDO::FETCH_NUM);
// Check if username exists in database
if ($rows > 0) {
// Check if passwords match
$sql = $connection->prepare("
SELECT password
FROM $DB_NAME.$TABLE_NAME
WHERE (username=:user);");
$sql->bindParam(":user", $username);
$sql->execute();
if (password_verify($password, $sql->fetch()[0]) > 0) {
echo "Username and password match";
} else {
echo "Username and password do not match";
}
} else {
echo "Username does not exist";
}