PHP中的用户名和密码问题


Username and Password trouble in PHP

我试图用PHP创建一个登录表单,但它无法登录。我得到了错误的密码/用户名。我已经三次检查了数据库中的凭据,它们是正确的。请帮助

这是代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<?php
     require('db.php');
     session_start();
     // If form submitted, insert values into the database.
     if (isset($_POST['username'])){
         $username = $_POST['username'];
         $password = $_POST['password'];
         $username = stripslashes($username);
         $username = mysqli_real_escape_string($connection,$username);
         $password = stripslashes($password);
         $password = mysqli_real_escape_string($connection,$password);
         //Checking is user existing in the database or not
         $query = "SELECT * FROM `backuser` WHERE username='".$username."' and password='".md5($password)."'";
         $result = $connection->query($query) or die(mysqli_error());
         $rows = mysqli_num_rows($result);
         if($rows==0){
             $_SESSION['username'] = $username;
             header("Location: index.php"); // Redirect user to index.php
         }else{
             echo " <div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
         }
     }else{
?>
<div class="form">
<h1>Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
</body>
</html>

您的逻辑中有一个错误。将if($rows==0)更改为if($rows!=0)。如果用户在DB中,则应至少返回1条记录,mysqli_num_rows()应返回一个数字>= 1

Sarasvati的回答似乎可以解决您的即时问题,但我也建议:

  • 使用内置的PHP密码哈希函数(PHP 5.5+和5.3)对密码进行哈希。MD5在密码方面不安全,不建议用于密码存储或检查。

  • 如果你是PHP的新手,那么在代码中使用Prepared Statements是非常值得花时间探索的。这将codeuser input分离开来,从而大大降低了SQL注入和数据库泄露的风险。

  • 当你有一个重定向的header时,你应该立即exit语句跟随这个头,因为在跟随这个头之前,PHP代码的其余部分仍将运行。

        $_SESSION['username'] = $username;
         header("Location: index.php"); // Redirect user to index.php
         exit;
    
  • 不要在密码字段上使用stripslashes()等文本编辑功能,如果有人的密码中有斜杠,它将被删除,他们将无法登录。密码应该是任何字符,而不仅仅是a-z或0-9等。

  • 对于MySQLi_[程序]错误报告,您需要提供连接详细信息:

    die(mysqli_error($connection));
    

    否则报告不会给你任何信息。

  • 在任何东西输出到浏览器之前,PHP session_start()应该是,所以它需要位于PHP页面的最顶部。(感谢Nitin,我最初错过了)。

问题是我没有在数据库中分配足够的存储空间(字符长度)来存储哈希值。我将长度值调整为30,它就像一个符咒。