Search code examples
phpsessionpassword-hash

Login system with password_verify()


I'm trying to make a login system with hashed passwords. What is supposed to happen is after I click on the submit button a session should be created and I should be redirected to home.php. If input data doesn't match the data inside the database I should get "Error 1" or "Error 2" alerts.

My problem is that when I click on a submit button all that happens is that I get redirected to login.php. I get no errors and no alerts, only blank screen with login.php URL.

I'm trying to figure how to make the password_verify() part work. Any kind of help is appreciated.

Picture of database: https://i.sstatic.net/OyBTK.jpg
Picture of what happens after a login attempt: https://i.sstatic.net/I2Myk.jpg

Form code:

<html>

<head>

<title> Login now! </title>

<meta charset="UTF-8">

<link rel="stylesheet" type="text/css" href="css/style.css"/>

</head>

<body>

<header>

  <div class="alignRight">
    <a href="registration.html"> Register </a> &nbsp; &nbsp;
  </div>

  <div class="alignLeft">
    <a href="contact.html"> Contact us </a> &nbsp; &nbsp; 
    <a href="aboutus.html"> About us </a> &nbsp; &nbsp;
    <a href="news.html"> News </a>
  </div>

</header>

<h1> Welcome back! </h1>

<h2> Log in to continue with your work. </h2> 

<form name="login-form" id="login-form" action="login.php" method="post">

    <input class="_40" type="text" name="username"  pattern="[a-zA-Z0-9_]{1,15}" 
placeholder="Username"  required /> 

    <br />

    <input class="_40" type="password" name="pwd"  placeholder="Password"  required />

    <br />

    <input id="loginSubmitButton" type="submit" value="Submit"  /> 

</form>

</body>

</html>

PHP code:

<?php


session_start();

$servername ="localhost";
$username = "root";
$password = "";

$link = mysqli_connect($servername, $username, $password);

mysqli_select_db($link, "users");


$username = mysqli_real_escape_string($link, $_POST["username"]);
$pwd = mysqli_real_escape_string($link, $_POST["pwd"]); 
$query = "SELECT * FROM users WHERE Username = '$username'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_assoc($result);

if(($result->num_rows > 0))
{
    while($row = mysqli_fetch_array($result))
    {
        if(password_verify($pwd, $row["Hash"]))
        {
            $_SESSION["username"] = $username;
            header("location:home.php");
        }
        else
        {
            echo '<script>alert("Error 1")</script>';
        }
    }
}
else
{
    echo '<script>alert("Error2")</script>';
}


?>

Solution

  • I think I see the problem.

    It looks like you're probably fetching the only row from the results before the if

    $row = mysqli_fetch_assoc($result);
    

    Then when you fetch again here, there's nothing left to fetch.

    if(($result->num_rows > 0))
    {
        while($row = mysqli_fetch_array($result))
    

    (I'm assuming the query will only return one row since username is unique.)