0v3k Shi3ld3r 0v3k Shi3ld3r - 10 months ago 27
MySQL Question

Decrypting Password Not working Login

I recently changed the hashing on passwords however since doing so I have had some issues with logging , I have registration working but cannot get my login to work can someone see why I keep getting wrong username or password .


if (isset($_POST['login'])){

$cookie_name = "loggedin";

// connection handler link
$con = new mysqli('localhost', 'xxx', 'xxx', 'xxx');
// in case theres no link to connection
if (mysqli_connect_error()){
echo mysqli_connect_error();
//echo "we good on connection so far";
echo "<br>";


// The (? ?) below are parameter markers used for variable binding
$sql = "SELECT * FROM `tbl1` WHERE `username` = ? ".
"AND `password` = ?";
if ( !$sql )
echo "Died on query";
die('mysqli error: '.mysqli_error($con));


// prepare function statement ,link
$stmt = $con->prepare($sql);

$user= $_POST['username'];
$user= mysqli_real_escape_string($con, $user);

//$pass= mysqli_real_escape_string($con, $pass)

$phash = password_hash($pass, PASSWORD_DEFAULT );

// bind variable parameters
mysqli_stmt_bind_param($stmt, "ss", $user , $phash); // bind variables s' is a string for username , s' is a string for password
if ( !mysqli_stmt_execute($stmt) )
echo "Died on bind variable parameters";
die( 'stmt error: '.mysqli_stmt_error($stmt) );


mysqli_stmt_execute($stmt); //excute the preapared login statement

if ($stmt->fetch())

// this line fails to verify password
$phash = password_verify($pass,$stmt);
echo "User logged in";

$cookie_value = $user;
setcookie($cookie_name , $cookie_value, time() + (8000), "/");

header("Location: ../index.php");
echo "<center>";
echo '<br />';
echo '<font color="red">Wrong username or password</font>';
echo "<hr>";

echo "Wrong username or password";
echo "</center>";
} // end else

} // end isset login

//register option

Thanks in advance for any help


You're problem is you are using an SQL statement to select based on username and password. This will not work because password_hash returns a different result every time because a unique salt is generated each time.

You have to select the user, then verify the password using password_verify. If it does not verify, they have not logged in.

Side note:

Your if ( !$sql ) check doesn't really do anything because it does not make any queries, you just created a string which will always be truthy.