PHP中的密码验证 [英] Password_verify in PHP
本文介绍了PHP中的密码验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我允许用户使用用户名和密码创建帐户.当用户使用以下方法创建新帐户时,我设法加密了密码:
So I'm enabling users to create accounts with a username and password. I have managed to encrypt the password when a user creates a new account using:
$hash = password_hash($password, PASSWORD_BCRYPT);
但是,我在登录时遇到 password_verify 问题,有人可以帮我解决问题吗?我知道是这样的:
However I'm having trouble with password_verify when logging in, could someone please help me with what I have? I know it's something like this:
password_verify($password, $hash)
但我不知道如何构造它或将它添加到代码中的何处.提前致谢.这就是我所拥有的:
But I don't know how to structure it or where to add it in the code. Thanks in advance. This is what I have:
<?php
if (isset($_GET["username"]) && isset($_GET["password"]) ){
$username = $_GET["username"];
$password = $_GET["password"];
$result = login( $username, $password);
echo $result;
}
function makeSqlConnection()
{
$DB_HostName = "";
$DB_Name = "";
$DB_User = "";
$DB_Pass = "";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
return $con;
}
function disconnectSqlConnection($con)
{
mysql_close($con);
}
function login($username, $password)
{
$con = makeSqlConnection();
$sql = "select * from login where username = '$username' and password = '$password';";
$res = mysql_query($sql,$con) or die(mysql_error());
$res1 = mysql_num_rows($res);
disconnectSqlConnection($con);
if ($res1 != 0) {
return 1;
}else{
return 0;
}// end else
}// end of Function
?>
推荐答案
一般做法如下:
- 从数据库中获取
password
哈希,其中username
= 输入的用户名. - 如果找到行,那么就有一个用户
- 现在您将输入的密码与存储在数据库中的哈希值进行比较.
- Fetch
password
hash from the database where theusername
= the inputted username. - If rows are found, then there's a user
- Now you compare the inputted password against the hash stored in the database.
<小时>
我将在此处用一些伪代码为您概述上述流程:
I'll outline the above flow in some pseudo code for you here:
$query = SELECT password FROM users WHERE username = '$username'
$data = FETCH_THE_DATA($query);
if(password_verify($USER_INPUTTED_PASSWORD, $data['password'])) {
// password is correct
} else {
// password is in-correct
}
<小时>
注意事项
- 停止使用
mysql_*
函数.该库已被弃用,因为它不可靠,并将在 PHP 的未来版本中删除.- 最好使用 PDO 或 MySQLi 准备好的语句
- Stop using
mysql_*
functions. The library is deprecated as it's unreliable and will be removed in future releases of PHP.- You're better off using PDO or MySQLi Prepared Statements
这篇关于PHP中的密码验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文