PHP: My first Login System wont verify Password

Viewed 74

Iv'e tried my first login system, and hang up at the verification of the password.

The query to check if the user exists works, but the check for the right password doesnt.

PHP:

<?php
  $user = $_POST['namex'];
  $host = "localhost";
  $username = "root";
  $password = "";
  $dbname = "mydb";
  $db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
  $stmt = $db->prepare("SELECT * FROM accounts WHERE username = :s");
  $stmt->bindParam(':s', $user);
  $stmt->execute();
  $count = $stmt->rowCount();
  if($count == 1)
  {
    $stmt2 = $db->prepare("SELECT password FROM accounts WHERE username =:s");
    $stmt2->bindParam(':s', $user);
    $stmt2->bindParam(':pw', $upw);       //here set the password from the database
    $inputpass = $_POST["pwx"];         //here set the input password
    if(password_verify($inputpass, $upw)){          //here try to check for the right input
      session_start();
      $_SESSION["namex"] = $user;            //here will start session for the input user
      echo "Youre logged in";
      //header("Location:loggedin.php");
    }
    else {
      echo "Password incorrect!";
    }
  }
  else{
    echo "This Account doesnt exists!";
  }
?>

HTML:

<form action="../login.php" method="post">
  <div>
    <input class="Namebox" id="namex" name="namex" required placeholder="Benutzername">
    <label for="namex" class="labelname"></label>
  </div>
  <div>
    <input type="password" class="pwbox" id="pwx" name="pwx" required placeholder="Passwort">
    <label for="pwx" class="labelpw"></label>
  </div>
  <button class="login" type="submit" value="submit">Anmelden</button>
</form>

Hope somebody can help me.

Regards Kevin

1 Answers

You don't need the second sql query, you can verify the password by editing the code as follows

  # ...

  $db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
  $stmt = $db->prepare("SELECT * FROM accounts WHERE username = :s");
  $stmt->bindParam(':s', $user);
  $stmt->execute();
  $count = $stmt->rowCount();
  if($count == 1)
  {
    $user = $stmt->fetch();
    $inputpass = $_POST["pwx"];        
    if(password_verify($inputpass, $user["password"])){         
      session_start();

  # ... 
Related