使用php password_verify的麻烦

时间:2018-02-17 03:53:12

标签: php

我对编程很陌生,而且我正在慢慢地通过Lynda php mysql essentials课程。我几乎完全通过了,但似乎密码无法验证。

<?php
require_once('../../private/initialize.php');

$errors = [];
$username = '';
$password = '';

if(is_post_request()) {

  $username = $_POST['username'] ?? '';
  $password = $_POST['password'] ?? '';

  // Validations
  if(is_blank($username)) {
    $errors[] = "Username cannot be blank.";
  }
  if(is_blank($password)) {
    $errors[] = "Password cannot be blank.";
  }

  // if there were no errors, try to login
  if(empty($errors)) {
    // Using one variable ensures that msg is the same
    $login_failure_msg = "Log in was unsuccessful.";

    $admin = find_admin_by_username($username);
    if($admin) {

      if(password_verify($password, $admin['hashed_password'])) {
        // password matches
        log_in_admin($admin);
        redirect_to(url_for('/staff/index.php'));
      } else {
        // username found, but password does not match
               //I output the password from the sql table just for debugging purposes                             
        $errors[] = $admin['hashed_password'];
      }

    } else {
      // no username found
      $errors[] = 'username';
    }

  }

}

?>

这是表格

<?php $page_title = 'Log in'; ?>
<?php include(SHARED_PATH . '/staff_header.php'); ?>

<div id="content">
  <h1>Log in</h1>

  <?php echo display_errors($errors); ?>

  <form action="login.php" method="post">
    Username:<br />
    <input type="text" name="username" value="<?php echo h($username); ?>" /><br />
    Password:<br />
    <input type="password" name="password" value="" /><br />
    <input type="submit" name="submit" value="Submit"  />
  </form>

</div>

<?php include(SHARED_PATH . '/staff_footer.php'); ?>

当我提交表单时,我收到有关密码的错误。我花了很长时间试图解决这个问题,似乎无法找到解决方案。这是我第一次发布堆栈溢出,所以如果有任何其他我应该发布的代码片段,请告诉我。

我收到的错误来自显示错误功能,它从表中输出密码,因为我设置了$ errors [] = $ admin ['hashed_pa​​ssword'];。我只是这样做,以确保我使用正确的密码。

function display_errors($errors=array()) {
  $output = '';
  if(!empty($errors)) {
    $output .= "<div class=\"errors\">";
    $output .= "Please fix the following errors:";
    $output .= "<ul>";
    foreach($errors as $error) {
      $output .= "<li>" . h($error) . "</li>";
    }
    $output .= "</ul>";
    $output .= "</div>";
  }
  return $output;
}

find_admin_by_username

function find_admin_by_username($username) {
    global $db;

    $sql = "SELECT * FROM admins ";
    $sql .= "WHERE username='" . db_escape($db, $username) . "' ";
    $sql .= "LIMIT 1";
    $result = mysqli_query($db, $sql);
    confirm_result_set($result);
    $admin = mysqli_fetch_assoc($result); // find first
    mysqli_free_result($result);
    return $admin; // returns an assoc. array
  }

0 个答案:

没有答案