PHP密码验证方法始终为false
这是我的login.php页面PHP密码验证方法始终为false,php,hash,passwords,Php,Hash,Passwords,这是我的login.php页面 <?php echo $loginError; ?> <form class="form-inline" action="<?php echo htmlspecialchars( $_SERVER['PHP_SELF'] ); ?>" method="post"> <div class="form-group"> <label for
<?php echo $loginError; ?>
<form class="form-inline" action="<?php echo htmlspecialchars( $_SERVER['PHP_SELF'] ); ?>" method="post">
<div class="form-group">
<label for="login-username" class="sr-only">Username</label>
<input type="text" class="form-control" id="login-username" placeholder="username" name="username">
</div>
<div class="form-group">
<label for="login-password" class="sr-only">Password</label>
<input type="password" class="form-control" id="login-password" placeholder="password" name="password">
</div>
<button type="submit" class="btn btn-default" name="login">Login!</button>
</form>
我要解决的第一个问题是转义,密码输入不应该转义,用原始输入调用password_hash()函数是安全的。因此,不要调用validateFormData()
,只需使用password\u散列($\u POST['password'])
。当然,password\u verify()
也是如此。输入验证是一件好事,但不是逃避,应该尽可能晚地只对特定的目标系统进行验证
代码中的另一个问题可能是重复的用户名。如果您不明确地检查现有用户名,您可能会有重复的用户名,那么您很可能会得到谁的密码哈希。我会考虑用电子邮件作为身份证
最后,您的代码容易受到SQL注入的攻击,请考虑使用准备好的语句。你可以在这里找到一个例子
include语句放在您获取密码后。因此,必须用数据库密码覆盖$password
变量。如何创建数据库中的密码?你用了吗?formPass=validateFormData($\u POST['password'])代码>
if( isset( $_POST['login'] ) ) {
// build a function to validate data
function validateFormData( $formData ) {
$formData = trim( stripslashes( htmlspecialchars( $formData ) ) );
return $formData;
}
// create variables
// wrap the data with our function
$formUser = validateFormData( $_POST['username'] );
$formPass = validateFormData( $_POST['password'] );
// connect to database
include('connection.php');
// create SQL query
$query = "SELECT username, email, password FROM users WHERE username='$formUser'";
// store the result
$result = mysqli_query( $conn, $query );
// verify if result is returned
if( mysqli_num_rows($result) > 0 ) {
// store basic user data in variables
while( $row = mysqli_fetch_assoc($result) ) {
$user = $row['username'];
$email = $row['email'];
$hashedPass = $row['password'];
}
// verify hashed password with the typed password
if( password_verify( $formPass, $hashedPass ) ) {
// correct login details!
// start the session
session_start();
// store data in SESSION variables
$_SESSION['loggedInUser'] = $user;
$_SESSION['loggedInEmail'] = $email;
header("Location: profile.php");
} else { // hashed password didn't verify
// error message
$loginError = "<div class='alert alert-danger'>Wrong username / password combination. Try again.</div>";
}
} else { // there are no results in database
$loginError = "<div class='alert alert-danger'>No such user in database. Please try again. <a class='close' data-dismiss='alert'>×</a></div>";
}
// close the mysql connection
mysqli_close($conn);
$formPass = validateFormData( $_POST['password'] );
// connect to database
include('connection.php');