Search code examples
phphtmlmysqlpassword-hash

PHP pasword_verify always saying password is valid except if column is empty


I'm not 100% sure I'm using PHP password verify correctly as it always says the the password entered from the form is valid. The part of my code I believe is having problems:

include('../connection/conn.php');
            $stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($db_email, $db_password);
            $count = $stmt->num_rows;
            //password hasing
            if ($count == 1)
            {
                while ($stmt->fetch()) {
                    if (password_verify($password, $db_password))
                    {
                        echo "Sucess";
                    }
            }
            }

I'll add int the conn.php file contents just in case anyone needs it

    <?php 
global $conn;
$server = "localhost";
$user = "root";
$password = "";
$db = "loginV2";
$conn = mysqli_connect($server, $user, $password, $db);

if (mysqli_connect_errno())
  {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
{

    echo "<p id='connection'>True</p>";
}

?>

Regardless of what password I entered into the form, "Success" is echo'd to the page of whether the correct password is entered. Here is the html form:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post"  name="input_form" onsubmit="return validateForm()">
                <label>Email:</label><br>
                <input type="text" name="email">
                <p class="error" id="email_Err"><?php echo $emailErr ?></p>
                <label>Password:</label>
                <input type="password" name="password">
                <p class="error" id="password_Err"><?php echo $passwordErr ?></p>
                <input type="submit" value="Sign Up">
            </form> 

My error is probably stupid but I've tried to learn password_verify and password_hash from the PHP manual and as far as I can tell, this code should work. Even if it's not well written, should function. Any help would be appreciated. Thanks.

Edit:

All this code apart from my mqysli_connect is within one PHP file "login.php". I'll insert the entirety of the code below:

    <!DOCTYPE html>
<html>
    <head>
        <title>Login</title>
        <link rel="stylesheet" type="text/css" href="style.css" >
        <link href="https://fonts.googleapis.com/css?family=Nunito:200" rel="stylesheet">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script>
            function validateForm()
            {
                var email = document.forms["input_form"]["email"].value;
                var password = document.forms["input_form"]["password"].value;
                var valid = true;
                if (email == null || email == "")
                    {
                        document.getElementById("email_Err").innerHTML = "Email is a required field";
                        valid = false;
                    }
                if (password == null || password == "")
                    {
                        document.getElementById("password_Err").innerHTML = "Password is a required field";
                        valid = false;
                    }

                if (valid === false)
                    {
                        $(function()
                         {
                            $( ".form_container" ).effect("shake");
                        });
                    }
                return valid;
            }

            $(function()
            {
                $('.form_container').hide().slideDown('slow');
            });
        </script>
    </head>

    <body>

        <?php 

        $email = $password = "";
        $emailErr = $passwordErr = "";
        $otherErr = "";
        if ($_SERVER["REQUEST_METHOD"] == "POST")
        {
            $dataErr = false;
            if (empty($_POST["email"]))
            {
                $emailErr = "Email is a required field";
                $dataErr = true;
            }
            else
            {
                $email = input($_POST["email"]);
                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $emailErr = "Invalid email "; 
                    $dataErr = true;
                }
            }

            if (empty($_POST["password"]))
            {
                $passwordErr = "Password is a required field";
                $dataErr = true;
            }
            else
            {
                $password = $_POST["password"];
                if (strlen($password) < 8)
                {
                    $passwordErr = "Invalid Entry";
                    $dataErr = true;
                }
            }


           //Suspected problem here 

        if (!$dataErr)
        {
            include('../connection/conn.php');
            //Duplicate Check
            $stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($db_email, $db_password);
            $count = $stmt->num_rows;
            //password hasing
            if ($count == 1)
            {
                while ($stmt->fetch()) {
                    if (password_verify($password, $db_password))
                    {
                        echo "Sucess";
                    }
            }
            }
        }   
        }

        function input($data) 
        {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
        }






        ?>
        <div class="form_container">
            <h2>Login</h2>
            <!--  -->
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post"  name="input_form" onsubmit="return validateForm()">
                <label>Email:</label><br>
                <input type="text" name="email">
                <p class="error" id="email_Err"><?php echo $emailErr ?></p>
                <label>Password:</label>
                <input type="password" name="password">
                <p class="error" id="password_Err"><?php echo $passwordErr ?></p>
                <input type="submit" value="Login">
            </form>
            <?php echo "<p style='text-align: center; color: red;'> " . $otherErr . "</p>" ?>
        </div>


    </body>
</html>

Thanks again


Solution

  • Found the error. 6hrs of var_dumps and the problem was in conn.php

    include('../connection/conn.php');
                //Duplicate Check
                $stmt = $conn->prepare("SELECT email, password FROM users WHERE email=?");
                $stmt->bind_param("s", $email);
                $stmt->execute();
                $stmt->store_result();
                $stmt->bind_result($db_email, $db_password);
                $stmt->fetch();
    

    Just before the password is verified the password we include conn.php to connect to the database. This is includes my database password is has the variable name as the user input password:

        <?php 
        global $conn;
        $server = "localhost";
        $user = "root";
    // $password is set to nothing
        $password = "";
        $db = "loginV2";
        $conn = mysqli_connect($server, $user, $password, $db);
    
        if (mysqli_connect_errno())
          {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }
        else
        {
    
            echo "<p id='connection'>True</p>";
        }
    
        ?>
    

    This meant that when password_verify was executed it was comparing $password from conn.php, which is blank. Changing the variables to connect to database resolved the problem.