gpt4 book ai didi

php - 我的登录 PHP 表单不起作用。我相信我的 $hash = $row ['password' ];是问题所在,但我不太确定

转载 作者:行者123 更新时间:2023-11-29 06:27:03 25 4
gpt4 key购买 nike

我目前正在使用 PHP 创建我的第一个网站。我创建了一个 MySQL 数据库,其中包含一个数据库和一个名为“users”的表,其中的列从左到右依次为“Personalid”(自动增量)、“用户名”和“密码”(使用 password_hash($POST_ ['密码'])

这是我的以下表单的 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'] 上,但我真的不知道。我的结果是数据库连接“已连接”,但始终“失败”,即使我输入正确的密码也是如此。当我输入错误的用户名时,它会显示“该用户不存在”,所以没有问题。

最佳答案

你几乎是正确的。哈希值应该来自数据库。更好的变量命名约定可能有助于发现错误。

我对您的脚本做了一些更改:

<?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();

通常,让其他人知道数据库中存在/不存在哪个用户是一个坏主意。只是说凭据不正确。

关于php - 我的登录 PHP 表单不起作用。我相信我的 $hash = $row ['password' ];是问题所在,但我不太确定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58885431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com