验证密码不起作用

z2acfund  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(378)

这个问题在这里已经有了答案

使用密码\u散列和密码\u验证[重复](1个答案)
两年前关门了。
我正在编写一个登录表单脚本,该脚本是从https://codeshack.io/secure-login-system-php-mysql/. 我已经完成了所有的步骤,但是每次单击login,我都会得到最里面的else语句错误“不正确的用户名和/或密码!”。我已确认我已正确连接到数据库。我的表中只有一行,因为我目前只处于测试阶段,我已经验证了我键入的密码是否正确。代码如下:

$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( mysqli_connect_errno() ) {
	// If there is an error with the connection, stop the script and display the error.
	die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data was submitted, isset will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
	// Could not get the data that should have been sent.
	die ('Username and/or password does not exist!');
}
// Prepare our SQL 
if ($stmt = $con->prepare('SELECT id, password FROM users WHERE username = ?')) {
	// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
	$stmt->bind_param('s', $_POST['username']);
	$stmt->execute(); 
	$stmt->store_result(); 
	// Store the result so we can check if the account exists in the database.
	if ($stmt->num_rows > 0) {
		$stmt->bind_result($id, $password);
		$stmt->fetch();      
		// Account exists, now we verify the password.
		if (password_verify($_POST['password'], $password)) {
			// Verification success! User has loggedin!
			$_SESSION['loggedin'] = TRUE;
			$_SESSION['name'] = $_POST['username'];
			$_SESSION['id'] = $id;
			echo 'Welcome ' . $_SESSION['name'] . '!';
		} else {
			echo 'Incorrect username and/or password!';
		}
	} else {
		echo 'Incorrect username and/or password!';
	}
	$stmt->close();
} else {
	echo 'Could not prepare statement!';
}

if(password\u verify)是当我想输入if语句以成功登录时,我点击else语句的位置。我对“selecting id,password from the db where username=?”有点怀疑,因为“username=?”不应该等于用户在名为username而不是“?”的输入字段中输入的内容吗(刚接触php和mysql-也许我的想法完全错了!)
有人知道发生了什么吗?我真的很感激你的帮助!
p、 我绝对肯定密码verify else是我收到的错误信息,因为在我这边,为了避免混淆,我把echo语句改成了下面的那个。

kuuvgm7e

kuuvgm7e1#

正如@funkfortyniner所建议的,我实现了一个密码散列函数:

$password = password_hash('password', PASSWORD_DEFAULT);

我的问题现在解决了。非常感谢你!

相关问题