我目前正在使用PHP创建我的第一个网站。我创建了一个MySQL数据库,该数据库具有一个数据库和一个名为“ users”的表,其中的列从左到右依次为“ Personalid”(AUTOINCREMENT),“ username”和“ password”(使用password_hash($POST_['password'])
散列。 / p>
这是我下面表格的HTML代码
<form method="post" action="idk.php">
<h1>Sign In</h1>
<br>
<input type="text" placeholder="Username" name="username"/>
<input type="password" placeholder="Password" name="password"/>
<button type="submit" name="submit" value="Login">Sign In</button>
</form>
这是我的php表单,名为idk.php
<?php
$conn=mysqli_connect('localhost','root','root',"user_hirsa");
if(!$conn){
die('Could not Connect My Sql:' .mysql_error());
}
else {
echo "Connected";
}
?>
<?php
$stmt = $conn->prepare("SELECT username, password FROM users WHERE username = ?");
$stmt->bind_param('s', $myusername);
$myusername = $_POST['username'];
$mypassword = $_POST['password'];
$hash = $row['password'];
$stmt->execute();
$stmt->bind_result($myusername, $mypassword);
$row = $stmt->fetch(); //fetch DB results
if (!empty($row)) { // checks if the user actually exists(true/false returned)
if (password_verify($mypassword, $hash)) {
echo 'success'; // password_verify success!
} else {
echo 'failed';
}
} else {
echo "This user does not exist"; //username entered does not match any in DB
}
$stmt->close();
$conn->close();
?>
我相信我的问题是$hash = $row['password']
,但是我真的不知道。对于数据库连接,我的结果是“已连接”,但即使输入了正确的密码也总是“失败”。当我输入错误的用户名时,它显示“此用户不存在”,因此那里没有问题。
答案 0 :(得分:2)
您几乎是正确的。哈希应该来自数据库。为您的变量使用更好的命名约定可能会有助于发现错误。
我对您的脚本进行了一些更改:
<?php
// enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('localhost', 'root', 'root', "user_hirsa");
// you should set the correct charset here
// $conn->set_charset('utf8mb4');
<?php
$myusername = $_POST['username'];
$mypassword = $_POST['password']; // plain password coming from login form
$stmt = $conn->prepare("SELECT password FROM users WHERE username = ?");
$stmt->bind_param('s', $myusername);
$stmt->execute();
// bind columns to variables
$stmt->bind_result($hashInDB);
$row = $stmt->fetch(); //fetch DB results
if ($row) { // checks if the user actually exists(true/false returned)
if (password_verify($mypassword, $hashInDB)) {
echo 'success'; // password_verify success!
} else {
echo 'failed';
}
} else {
echo "This user does not exist"; //username entered does not match any in DB
}
// you don't need these
// $stmt->close();
// $conn->close();
通常,让其他人知道数据库中存在/不存在哪个用户是个坏主意。只需说凭据不正确即可。
答案 1 :(得分:0)
似乎您试图在实例化$ row之前访问它。因此,您的$ hash将为null。检索结果后尝试设置哈希值。
$row = $stmt->fetch();
$hash = $row['password'];