douxia6554 2017-10-18 14:18
浏览 85
已采纳

密码无法在我的login.php中验证[重复]

This question already has an answer here:

When I register, it hashes the password and then puts the username and the hashed password into my local database. Works fine. When I try to login, the username and password don't match any in the local database and it throws me the error message called login=error2 into the url, which I have written for the case if something is wrong in that part of the code. So you should look for error2 in login.php. I assume the problem lies there. I have been stuck on it the entire day and can't get it to work.

p.s. I am a front-end dev and the most complicated frameworks I use are jquery and react, so I am sorry if I may sound stupid regarding php/mysql. I started learning php 3 days ago.

I am using XAMPP localhost at port 80, this is the phpmyadmin sql code I used (database name is pixl_users)

create table user_info ( username varchar(12) not null, password varchar(30), email varchar(30), gender int(1), date datetime not null );

$(document).ready(function () {
  //switch to login form
  $('#switch-to-login').click(function () {
    $('#form-register').hide();
    $('#form-login').show();
  });
  //switch to registration form
  $('#switch-to-signup').click(function () {
    $('#form-login').hide();
    $('#form-register').show();
  });
});

========================================

signup.php file

<?php


if (isset($_POST['register'])) {

  include_once 'db-connect.php';

  $username = mysqli_real_escape_string($conn, $_POST['username']);
  $password = mysqli_real_escape_string($conn, $_POST['password']);

  if ((empty($username) || empty($password)) || $username == "admin" || $username == "Admin") {
    // if fields are empty, send back to index and say error msg
    header("Location: index.php?fields=empty");
    exit();
  } else {
    // check for characters which are not allowed in the registration fields
    if (!preg_match('/^[a-zA-Z0-9_.\s]+$/i', $username) || !preg_match('/^[a-zA-Z0-9_.!\s]+$/i', $password)) {
      header("Location: index.php?fields=invalidcharacters");
      exit();
    } else {
        //check if username is longer than 2 and shorter than 13 characters
        if (strlen($username) > 2 && strlen($username) < 13) {
          // check if username is taken
          $sql = "SELECT * FROM user_info WHERE username='$username'";
          $result = mysqli_query($conn, $sql);
          $resultCheck = mysqli_num_rows($result);

          if ($resultCheck > 0) {
            header("Location: index.php?fields=userTaken");
            exit();
          } else {
            //hashing the password
            $hashedPass = password_hash($password, PASSWORD_DEFAULT);
            //insert the user into the database
            $insert = "INSERT INTO user_info (username, password)
            VALUES ('$username', '$hashedPass')";
            //query it into the database
            mysqli_query($conn, $insert);
            //send user to the main website page
            header("Location: index.php");
          }

        } else {
          echo "Username can't be shorter than 3 characters and longer than 12 characters!";
        }


    }
  }

}
login.php file


<?php

session_start();

if (isset($_POST['login'])) {
  // connect to local database
  include 'db-connect.php';
  // get username and password from inputs
  $username = mysqli_real_escape_string($conn, $_POST['login-username']);
  $password = mysqli_real_escape_string($conn, $_POST['login-password']);

  //check if fields are empty
  if (empty($username) || empty($password)) {
    header("Location: index.php?fields=empty");
    exit();
  } else {
    // put usernames from table into array $resultCheck
    $sql = "SELECT * FROM user_info WHERE username='$username'";
    $result = mysqli_query($conn, $sql);
    $resultCheck = mysqli_num_rows($result);
    // if there is 0 usernames in database throw error
    if ($resultCheck < 1) {
      header("Location: index.php?login=error1");
      exit();
    } else {
      if ($row = mysqli_fetch_assoc($result)) {
        //De-hashing the password
        $hashedPassCheck = password_verify($password, $row['password']);
        if ($hashedPassCheck == false) {
          header("Location: index.php?login=error2");
          exit();
        } elseif ($hashedPassCheck == true) {
          // log in the user
          $_SESSION['user_name'] = $row['username'];
          header("Location: index.php?login=success");
          exit();
        }
      }
    }
  }

} else {
  header("Location: index.php?login=error");
  exit();
}
<?php session_start(); ?>

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>database test</title>
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <style>
    body {
      background-color: black;
      color: white;
    }
    
    #form-register {
      display: none;
    }
  </style>
</head>

<body>

  <button id="switch-to-login">switch to login</button>
  <button id="switch-to-signup">switch to signup</button>
  <!-- register -->
  <form id="form-register" action="signup.php" method="POST">
    <input id="inp-username" type="text" name="username" placeholder="choose a name" /><br />
    <input id="inp-password" type="password" name="password" placeholder="choose a password" />
    <button id="btn-register" name="register" type="submit">Register</button>
  </form>
  <!-- login -->
  <form id="form-login" action="login.php" method="POST">
    <input id="inp-username" type="text" name="login-username" placeholder="login name" /><br />
    <input id="inp-password" type="password" name="login-password" placeholder="password" />
    <button id="btn-login" name="login" type="submit">Login</button>
  </form>


  <script src="script.js"></script>
</body>

</html>

</div>
  • 写回答

1条回答 默认 最新

  • dongzhuo1930 2017-10-18 15:09
    关注

    If you call $hash = password_hash($newRegistrantPassword, PASSWORD_DEFAULT) more than once, you'll get a different $hash every time even if the password you give it is the same. That's because the function generates a different random hash each time. (If you're curious about why, look up rainbow tables.)

    If you store $hash in a database column that doesn't have enough characters in it, you'll truncate it. That's bad. Future proof your application by using VARCHAR(255) for the hashed password.

    What do I mean by future proof? The php developers recognize that computers get faster and cybercreeps get smarter and passwords get easier to crack. So they added the password_needs_rehash() function . In future releases of php, they may change the PASSWORD_DEFAULT hash methodology, making hashes harder to crack.

    Good password verification code for an application expecting a long life might look like this.

      $valid = password_verify ( $passwordPresentedByUser, $storedHash );
      if ( $valid ) {
        if ( password_needs_rehash ( $storedHash, PASSWORD_DEFAULT ) {
          $newHash = password_hash( $passwordPresentedByUser, PASSWORD_DEFAULT );
          /* UPDATE the user's row in the database to store $newHash */
        }
        /* log the user in, have fun! */
      }
      else {
        /* tell the would-be user the username/password combo is invalid */
      }
    

    To troubleshoot your hashing, try putting these lines of code in your php program, and see what happens:

     $myFakePassword = 'BompSheBomp!Wow';
     $hash = password_hash( $myFakePassword, PASSWORD_DEFAULT );
     var_dump( $hash );
     $valid = password_verify ( $myFakePassword, $hash );
     if ( $valid ) echo 'Hey! It worked!';
     else echo 'WTF? password verify didn't work.';
    

    Then make sure you store the hashed password in your database when you register a new user. When a user tries to log in, make sure you use password_verify to check the stored, hashed, password against the one furnished by your user.

    You can verify a hashed password. But you can't unhash it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献