password_verify() does not match with password in database - php

I am creating a user login page. I used password($pass,PASSWORD_BCRYPT) in inserting the data into the database but on trying to verify the password with password_verify($password,$salt) the values does not match.
I am sure that the data $salt retrieved from the database is correct but it does not match. Can you advise how I can troubleshoot it further? I have searched this thoroughly but cant find any answer.
This is my login code below:
<?php
// if form submitted
// check supplied login credentials
// against database
}
else { $username = $_POST['username'];
$password = $_POST['password'];
// check input
if (empty($username)) {
die('ERROR: Please enter your username');
}
if (empty($password)) {
die('ERROR: Please enter your password');
}
// attempt database connection
include("memberconnect.php");
$pdo = new mysqli($host,$user,$password,$database);
if (!$pdo) {
die("ERROR: Could not connect: (" . $pdo->errno .")" .$pdo->error);
}
// escape special characters in input
$username = stripslashes($username);
// check if usernames exists
$sql = "SELECT Login_Name FROM memberdirectory WHERE Login_Name = '$username ' ";
if ($result = mysqli_query($pdo,$sql)) {
$row = mysqli_num_rows($result);
// if yes, fetch the encrypted password
if ($row == 1) {
$sql = "SELECT Password FROM memberdirectory WHERE Login_Name = '$username' ";
// encrypt the password entered into the form
// test it against the encrypted password stored in the database
// if the two match, the password is correct
if ($result = mysqli_query($pdo,$sql)) {
$row = mysqli_fetch_array($result);
$salt = $row[0];
if (password_verify($password,$salt))
{
// password correct
// start a new session
// save the username to the session
// if required, set a cookie with the username
// redirect the browser to the main application page
session_start();
$_SESSION['username'] = $username;
if ($_POST['sticky']) {
setcookie('name', $_POST['username'], mktime()+86400);
}
header('Location: main.php');
}
else
{ echo 'You entered an incorrect password.';
echo strlen($salt);
var_dump(password_verify('$password',$salt));
var_dump($salt);
}
}
else {
die("ERROR: Could not execute $sql (" .$pdo->errno.")".$pdo->error);
}
} else {
echo 'You entered an incorrect username.';
}
} else {
die( "ERROR: Could not execute $sql (" .$pdo->errno.")".$pdo->error);
}
// close connection
unset($pdo); }
?>

password_verify checks the password against a hash. To get the hash, which by the looks would be saved to the database, you would use password_hash. This is even stated in password_verify php.net manual pages. Please recheck your hashing.
The only password function I am aware of is for MySQL that is used mainly for MySQL authentication. If you are using a custom function password, you will have to resend the entered password and salt through or reverse engineer the hash.

Related

the second condition of my login function is not working

i am trying to set a login function which match the username and the password existing in my database However the first condition is working perfectly but not the second one
<?php
if(isset($_POST['loginButton'])){
//taking user input
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
//Call of the login function through acccount variable
$result = $account->login($username, $password);
if($result == true){
header('location:index.php');
}
}
?>
<?php
class Account{
...
public function login($un , $pw){
$pw = md5($pw);
$query = mysqli_query($this->con , "SELECT * FROM users WHERE username = '$un' AND passwords = '$pw' ");
if(mysqli_num_rows($query) == 1){
return true;
}
else{
array_push($this->errorArray , Constants::$loginFailed);
return false;
}
}
}
?>
<?php
class Constants{
//Login constants
public static $loginFailed = "Your username or password was incorrect";
}
?>
i except it to return true so it will redirect me to the index page but actual input is false
Your Query will always return false, because it is not able to find the user with the given password, it is not the correct way to verify hashed password
//this is where the problem is, do not verify password like this:
$pw = md5($pw);
$query = mysqli_query($this->con , "SELECT * FROM users WHERE username
= '$un' AND passwords = '$pw' ");
This is the correct way of verifying hashed passwords (https://www.php.net/manual/en/function.password-verify.php):
if (password_verify($pw, $hash)) { //$hash password is from the DB
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
So In your sql Query get the user with the given username first
$query = mysqli_query($this->con , "SELECT * FROM users WHERE username = '$un'");
then Match the password from the DB with the current user given password $pw with password_verify function. so it will be something like this:
if($query){
$data = mysqli_fetch_row($query);
if (password_verify($pw, $data['passwords'])) { //$data['password'] password is from the DB
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
}

Cannot Compare with md5 password from database

signup.php
$password_unencrypted = $_POST['passwd'];
$password=md5($password_unencrypted);
$query = "INSERT INTO Customers (firstname, lastname, username, password, " . "gender,mobile,email) " . "VALUES ('$first_name', '$last_name', '$user_name', '$password', " . " '$gender','$mobile','$email')";
Login.php
$username=$_POST['username'];
$password=md5($_POST['password']);
$sql = ("select * from Customers where username='".$username."' and password='".$password."'") or die('Error connecting to MySQL server.');
$query = mysqli_query($con,$sql);
$result=mysqli_fetch_row($query);
if($result)
{
$_SESSION['username']=$username;
header('location:home.html');
}
else
{
echo md5($_POST['password']);
echo 'Your entered username or password is incorrect';
}
In above signup and login codes I'm applying md5 for password storing
I checked in Database the md5 password is storing correctly but is not retreiving properly(i think)
trying to login into page it is failing
FYI : echo md5($_POST['password']); in Login.php is showing same password stored in database
here is it how to fix your login.php code
you were totally checking wrong you need to check first if the query succeeded running then check if returned rows are more than 0 that means the username is correct and we proceed to password checking if everything is fine we start the session assuming you have session_start() on top of your page if not add it before $_SESSION['username'] = $username;
check the manual for password_hash() and password_verify()
on register.php modify saving the password into the database
$password = md5($_POST['password']); to $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
<?php
if isset($_POST['submit']) {
$username= mysqli_real_escape_string($con, trim($_POST['username']));
$password = trim($_POST['password']); // no need to sanitize the password
$sql = "select * from Customers where username = '" .$username."' "; // you don't need or Die() it's just a string
if ($result = mysqli_query($con,$sql)) //check if the Query succeeded running
{
$count = mysqli_num_rows($result);
if($count > 0 )
{ // if username exists we proceed to checking password
$fetch = mysqli_fetch_assoc($result);
$hashedpassword = $fetch["password"];
if ( password_verify($password, $hashedpassword) )
{ //checking password
$_SESSION['username']=$username;
header('location:home.html');
exit;
}else {
echo "incorrect username or password"; // you don't want to tell him that the username is fine but the password is not correct
}
} else {
echo "incorrect username or password";
}
} else {
echo 'Query failed to run';
}
}
?>

Issues Verifying Login access with Bcrypt Password Even After calling the verification function

And here's the latest change to my login process. I want to verify if the user's input matches with the hashed password that has been stored in the database.
if(!isset($error)){
//Use the input username and password and check against 'users' table
$query = mysql_query("SELECT * FROM users
WHERE username = '".mysql_real_escape_string($user_input)."' OR email = '".mysql_real_escape_string($user_input)."' LIMIT 1")
or die(mysql_error());
$count_row = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
if($count_row == 1){
$hashed_password = $row['password'];
if(! password_verify($password, $hashed_password)){
$error[] = "Login failed! Please check your entered email and/or password";
} else if($row['active'] < 1){
$error[] = "Account has not been activated.";
}else if($row['active'] == 1){
// Do nothing
} else {
//write user data into PHP SESSION
This is my latest code. Any help is appreciated. Thanks in advance.
You're hashing the user password with this :
$password = password_hash($password, PASSWORD_BCRYPT);
However, during the login phase, you're doing the following :
$password = strtolower($email) . $password;
Since you're comparing the hashed of two different String, you won't get what you want.

How to set user/admin accounts for a redirect after log in? PHP

My problem with this code is that the IF statement which is deciding what page to go to seems to default to index.php. I have made a login table in MySQL already and have username/password column, and another column with a boolean value which states if the user is admin.
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$count = mysql_num_rows($result);
$auth = $row['admin'];
if ($count == 1) {
if ($auth['admin'] == 1) {
session_start();
$_SESSION['admin'] = $auth;
$_SESSION['username'] = $username;
header("location: member.php");
} elseif ($auth['admin'] == 0) {
session_start();
$_SESSION['admin'] = $auth;
header("location:index.php");
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Since you already extracted your admin value here:
$auth=$row['admin'];
You don't have to extract it here:
if($auth['admin']==1){
or here:
elseif($auth['admin']==0){
This simple change should fix your problem:
if($auth==1) {
...
} elseif($auth==0) {
...
In your original code, $auth['admin'] doesn't exist because $auth itself is just an integer, so it will pass the $auth['admin'] == 0 test since it is "falsy."
Also, it looks like you may have a case where $auth is completely undefined, in which case you should use "strict comparison" for that second condition, so you're looking for an actual zero and not just anything falsy:
} elseif($auth===0) {
I re wrote your login script. Try this. I think you'll find this will work much better for what your doing.
if(isset($_POST['username'])) {
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$password = $_POST['password'];
//$password = md5($password);
$db_host = "host"; $db_username = "username"; $db_pass = "password"; $db_name = "db_name"; mysql_connect("$db_host","$db_username","$db_pass"); mysql_select_db("$db_name"); // connect to your database only if username is set
$sql = mysql_query("SELECT * FROM login WHERE username='$username' and password='$password'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){ // if the user exists run while loop below
session_start(); // start session here (only once)
while($row = mysql_fetch_array($sql)){ // fetch the users admin from query
$auth = $row['admin'];
$_SESSION['admin'] = $auth; // set admin session variable
$_SESSION['username'] = $username; // set username session variable
if($auth == 1){
header("location: member.php"); // if user auth is 1, send to member
}else if($auth == 0){
header("location: index.php"); // if user auth is 0, send to index
}
exit();
}
} else {
header('Location: login.php'); // if user doesnt exist, reload login page.
}
mysql_close();
}
I recommend using md5 hash passwords.
When a person registers at your site, you can convert the password to md5 hash with this line $password = md5($password); prior to the db entry
Regarding your $auth above, this assumes your entry in the database is either a 0 or a 1. If you are controlling it this way, i recommend using enum in the sql database. set the type to "enum" and the type to '0', '1'
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result=mysql_query($query) or die(mysql_error());
$row= mysql_fetch_array($result);
$count=mysql_num_rows($result);
$auth= (int)$row['admin'];
if($count){
if($auth == 1){
$_SESSION['admin']= $auth;
$_SESSION['username']= $username;
header("location: member.php");
exit;
}elseif($auth == 0){
$_SESSION['admin']= $auth;
header("location:index.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
Try
header("Location: index.php");
exit;
header("Location: member.php");
exit;
Note the Capital L and the exit;
Also try if($auth == "1") and elseif($auth == "0") respectively.
If you value the security of your login page, use PDO or mysqli instead of mysql. It is deprecated and insecure due to its vulnerability to SQL injection.
Also, take advantage of PhP's password_hash and password_verifywhen handling storage and verification of passwords. It is a lot more secure compared to md5(). If you'd like examples of usage, let me know.

Validate email with database

I have created a form and have validated everything using PHP, but can't figure out how to validate email from database. If I have the entered username in the database, I want it to display an error. I have connect.php and
just for an example -
here's how i validate password -
if(!empty($_POST['password']))
{
if($_POST['password'] != $_POST['cpass'])
{
$errors[] = 'The password and confirm password do not match.';
}
else
{
$p=trim($_POST['password']);
}
}
here is what i'm trying to do -
$getusername = "SELECT username FROM users WHERE ($u,$username)";
if($getusername)
{
echo 'Username is already in use.';
}
else
{
$g=trim($_POST['username']);
}
THIS RESULTS IN A PARSE ERROR.
// first define the username from the $_POST variable
// make sure to escape the value to prevent SQL injection
$username = mysql_real_escape_string(trim($_POST['username']));
// select a user with the posted username
$sql = "SELECT username FROM users WHERE username = '$username' LIMIT 1";
// run the query
$res = mysql_query($sql) or die(mysql_error());
// see if there's a result
if (mysql_num_rows($res) > 0) {
echo 'This username is already taken';
} else {
// .. do stuff
}

Categories