Jump to content

Invalid password when using password_verify


Go to solution Solved by mac_gyver,

Recommended Posts

Hi

In my registration page I am taking the password as hashed as below:

register.php:

<?php
    session_start();
    include("header.php");

    $user_email = "";

    $email_error = "";
    $user_password_error = "";
    $confirm_password_error = "";
    $admin_password_error = "";
    $isadmin = 0;

    if($_SERVER["REQUEST_METHOD"] == "POST") 
    {

      $user_email = $_POST["email"];
      $user_password = $_POST["password"];
      $confirm_password = $_POST["confirmpassword"];
      $admin_password = $_POST["adminpassword"];
      $isadmin = $_POST["isadmin"];
      $error = false;

      $hashedPass = password_hash($user_password, PASSWORD_DEFAULT);

      include('connect.php');
      $sqlSelect = "SELECT username_email FROM login_users where username_email = '$user_email'";
      $result = mysqli_query($conn,$sqlSelect);
      $count = mysqli_num_rows($result);
      
      if ($count == 1) 
      {
        $email_error = "user email is already in use!";
        $error = true;
      }
      else 
      {
        if ($isadmin == 1) 
        {
          if ($admin_password == "???")
          {
            $sqlInsert = "INSERT INTO login_users(username_email,password,IsAdmin) VALUES       ('$user_email','$hashedPass','$isadmin')";    
            if(mysqli_query($conn,$sqlInsert))
            {
                session_start();
                header('Location: http://www.ramiwahdan.org/login.php', true);
            }
            else
            {
              die("Something went wrong");
            }
          }
          else
          {
            $admin_password_error = "You entered the wrong Admin Password!";
            $error = true;
          }
        }
        else 
        {
          $sqlInsert = "INSERT INTO login_users(username_email,password,IsAdmin) VALUES ('$user_email','$hashedPass','$isadmin')";    
          if(mysqli_query($conn,$sqlInsert))
          {
            session_start();
            header('Location: http://www.ramiwahdan.org/login.php', true);
          }
          else
          {
            die("Something went wrong");
          }
        }
      }
    }
?>

in my login page I am checking if the entered password is the same as the one in my database but I am getting wrong password message, why is that?

login.php:

$test2 = 1;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
   $myusername = mysqli_real_escape_string($db,$_POST['email']);
   $mypassword = mysqli_real_escape_string($db,$_POST['password']);
      
   $sql = "SELECT * FROM login_users WHERE username_email = '$myusername' and IsAdmin = $test2";
   $result = mysqli_query($db, $sql);
   $count = mysqli_num_rows($result);

  if($count == 1) 
  {
      // $row['password'] is hashed from the above register.php code
      while($row = $result->fetch_assoc()) {
          if (password_verify($mypassword, $row['password'])) {
              echo 'Password is valid!';
          } else {
              echo 'Invalid password.';
          }
       }
       exit();
  }
}

Why is that?

I made the code more readable and was being able to get some results but a disappointing one!

when using the verify it is giving me that the password is not correct, I know it is correct, why?

main.php code:

<?php 
        session_start();
	//include("header.php");
	include("config.php");

	if ($_SESSION['admin'])
	{
	   include("header.php");
           include("admin_page.php");
	}

	if ($_SESSION['user'])
	{
	   include("header.php");
           include("welcome.php");
	}

   $myusername = '';
   $mypassword = '';
   $test1 = 0;
   $test2 = 1;
   $error='';
   
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $myusername = mysqli_real_escape_string($db,$_POST['email']);
      $mypassword = mysqli_real_escape_string($db,$_POST['password']);
      
      $sql = "SELECT * FROM login_users WHERE username_email = '$myusername'";
      $result = mysqli_query($db, $sql);
      $count = mysqli_num_rows($result);

	if($count == 1) 
      	{
		while($data = mysqli_fetch_array($result))
                {
		  if (password_verify($_POST['password'], $data['password']))
	      {
		         if ($data['IsAdmin'] == $test2)
                 {
                      $_SESSION['admin'] = $_POST['email'];
	   	              include("header.php");
           	          include("admin_page.php");
		              header('Location: https://www.ramiwahdan.org/main.php');   
                 }

                 else
                 {
                    $_SESSION['user'] = $_POST['email'];
	                include("header.php");
                    include("welcome.php");
                 }
		  }
          else
          {
			 echo "error!";
          }
		}

 

Are you storing your password as a plain text in the database? If yes, then password verify won't work. But if no, and properly hashed this version should work.

session_start();
include("config.php");

$test1 = 0;
$test2 = 1;
$error = '';

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    $myusername = mysqli_real_escape_string($db, $_POST['email']);
    $mypassword = mysqli_real_escape_string($db, $_POST['password']);

    $sql = "SELECT * FROM login_users WHERE username_email = '$myusername'";
    $result = mysqli_query($db, $sql);
    $count = mysqli_num_rows($result);

    if ($count == 1)
    {
        $data = mysqli_fetch_array($result);

        if (password_verify($mypassword, $data['password']))
        {
            if ($data['IsAdmin'] == $test2)
            {
                $_SESSION['admin'] = $myusername;
                header('Location: admin_page.php');
                exit();
            }
            else
            {
                $_SESSION['user'] = $myusername;
                header('Location: welcome.php');
                exit();
            }
        }
        else
        {
            $error = "Invalid password.";
        }
    }
    else
    {
        $error = "User not found.";
    }
}

if (isset($_SESSION['admin'])) {
    include("header.php");
    include("admin_page.php");
}
elseif (isset($_SESSION['user'])) {
    include("header.php");
    include("welcome.php");
}

 

Edited by Olumide
  • Solution
Posted (edited)

the most common reason for a password_hash()/password_verify() to fail is because the database column is not long enough to hold the hashed value.

another common reason are programming mistakes in the form/form processing code and a lack of server-side validation that results in the hash value not actually being from the password that was submitted in the registration code, or the value being used in the login code not being what you think it is. your post method form processing code should always trim the input data, mainly so that you can detect if all white-space characters were entered, then validate all inputs before using them.

Edited by mac_gyver
  • Like 2
  • 2 weeks later...
On 4/22/2025 at 3:32 PM, mac_gyver said:

the most common reason for a password_hash()/password_verify() to fail is because the database column is not long enough to hold the hashed value.

This is correct, the length of string produced by password_hash() with default algorithm (bcrypt, as of now) is always 60 characters.

So if you do 

password_hash('mypassword', PASSWORD_DEFAULT);

and your database column can only store less than 60 characters, it will be truncated with some error being thrown

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.