password_verify() always return false - php

I am a newbie and I was trying to create a login system using PHP and Mysql. After finishing registration form and adding few users, I was trying to create a login form. but it always returns false saying my your Your username or password is incorrect!. Below is my code. It will be great if someone could help me. Advance sorry if my doubt is tooo basic :/
<?php
session_start();
include '.\includes\functions\db.php';
?>
<?php
$username = strtolower(mysqli_real_escape_string($db, $_POST['username']));
$password = strtolower(mysqli_real_escape_string($db, $_POST['password']));
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['password'];
echo $hash_pwd;
echo $password;
$hash = password_verify($password, $hash_pwd);
if ($hash ==0) {
header("Location: ./index.php?error=check");
exit();
}else {
$sql = "SELECT * FROM user WHERE username = '$username' AND password = '$hash_pwd'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 0) {
echo "Your username or password is incorrect!";
}else {
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
}
//header("Location: ./index.php");
}
?>
and my registration page is as follows
<?php
//This Page is for registration of users
?>
<?php
// this php tag is for all includes
include '.\includes\functions\db.php';
?>
<?php
//print isset($_POST["submit"]);
//Getting all details inserted in form
if(isset($_POST["register"])){
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$date = date('Y-m-d H:i:s');
//Encrypting and Securing recieved data
$username = strtolower(mysqli_real_escape_string($db, $username));
$firstname = strtolower(mysqli_real_escape_string($db, $firstname));
$lastname = strtolower(mysqli_real_escape_string($db, $lastname));
$email = strtolower(mysqli_real_escape_string($db, $email));
$password = strtolower(mysqli_real_escape_string($db, $password));
$encryptedpassword = password_hash($password, PASSWORD_DEFAULT);
//To check duplication of email ids
$sql = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($db, $sql);
$row = mysqli_num_rows($result);//$row will return count of rows if any duplicate email ids are found
//To check duplication of usernames
$sql2 = "SELECT username FROM users WHERE username='$username'";
$result2 = mysqli_query($db, $sql2);
$row2 = mysqli_num_rows($result2);//$row2 will return count of rows if any duplicate usernames are found
//conditions to check what all duplicates are found
if($row > 0 && $row2 >0){
echo "Sorry...This email id and username is already taken!!!";
} elseif ($row > 0 ) {
echo "Sorry...This email id is already taken!";
} elseif ($row2 > 0) {
echo "Sorry...This Username is already taken!";
}else {
$query = mysqli_query($db, "INSERT INTO users (username, firstname, lastname, password, email, regdate) VALUES
('$username', '$firstname', '$lastname', '$encryptedpassword', '$email', '$date')");
if($query){
echo "Thank You! you are now registered.";
}
}
}
?>

The error in my code is because of password = '$hash_pwd' condition in my where clause. When i retried row with given username and later verified password using php, it works as intended. I guess password hashed in php using password_hash() cannot be retrived and verified like encryption. Anyway thanks for all of yours responses

Related

Can't login using password_verify

I'm trying to make a register/login system. The hashed passwords are saved into database successfully but when i try to login it says "Invalid login" which means it doesn't verify the password. Help me with this, it's my first time using password hash and verify
Signup.php
<?php
include('AdminPanel/connect.php');
$name = $_POST['txt_name'];
$email = $_POST['txt_email'];
$password = password_hash($_POST['txt_pass'], PASSWORD_DEFAULT);
$radioVal = $_POST['Gender'];
if($radioVal == "Male")
{
$radioVal = "Male";
}
else if ($radioVal == "Female")
{
$radioVal = "Female";
}
$queryget = mysqli_query($con,"SELECT Email FROM signup WHERE Email='$email'") or die ("Query didnt work");
$row = mysqli_fetch_array($queryget);
$emaildb = $row['Email'];
if($emaildb!=$email){
echo"success";
$insert = mysqli_query($con,"insert into signup (Name,Email,Password,Gender) values ('$name','$email','$password','$radioVal')");
}else{
echo"Email already exists";
}
?>
Login.php
<?php
include('AdminPanel/connect.php');
session_start();
$email = $_POST['txt_email'];
$password = $_POST['txt_pass'];
$info = mysqli_query($con,"select count(*) from signup where Email = '$email' and Password = '$password'");
$row = mysqli_fetch_array($info);
if (($row[0] > 0) && password_verify($password, $row['Password']))
{
$_SESSION['txt_email']=$email;
echo "success";
}
else
{
echo "Invalid login<br>Please re-enter your credentials";
}
?>
You're selecting count(*):
$info = mysqli_query(
$con, "select count(*) from signup where Email = '$email' and Password = '$password'"
);
But then referencing a field:
$row['Password']
You need to select (at least) the field, but leave out the condition on password because the password you get won't match what's in the database:
$info = mysqli_query(
$con, "select * from signup where Email = '$email'"
);
Also, don't do that, because SQL injection.

Password Hashing Not Working For MySQL

I have been on here all day and looked at all of the answered wuestions and also looked at tutorials online regarding password hashing. It seems as though I am doing it right and it hashes the password in the database but when I go to login it tells me that the password is incorrect. Here is the script, any help would be greatly appreciated.
Login.PHP
if (isset($_POST['username'])){
//escapes special characters in a string
$username = stripslashes($_REQUEST['username']);
$username = mysqli_real_escape_string($con,$username);
$password = $_REQUEST['password'];
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$hash = $row['password'];
if (password_verify($password, $hash)) {
$_SESSION['username'] = $username;
// Redirect user to index.php
$position = $row['position'];
if ( $position == "freelancer" ){
header("Location: ../freelancer/index.php");
}
elseif ($position == "employer"){
header("Location: ../employer/index.php");
}
}
else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
".$hash." " .$password. "
<br />Click here to <a href='login.php'>Login</a>
</div>";
Register.PHP (Piece of Code that Hashes the Password)
//BEGINNING CODE HERE
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$hashPassword = password_hash($password, PASSWORD_DEFAULT);
$sql_u = "SELECT username FROM users WHERE username='$username'";
$sql_e = "SELECT email FROM users WHERE email='$email'";
$res_u = mysqli_query($con, $sql_u);
$res_e = mysqli_query($con, $sql_e);
if (mysqli_num_rows($res_u) > 0) {
$name_error = "Sorry... username already taken";
}
else if(mysqli_num_rows($res_e) > 0){
$email_error = "Sorry... email already taken";
}
else{
$query = "INSERT INTO users (username, email, password)
VALUES ('$username', '$email', '$hashPassword')";
$results = mysqli_query($con, $query);
mkdir("../profilePics/" . $username);
echo 'You Have Registered Successfully!<br>
To Login Go To Our Login Page
';
exit();
}
}
?>
I know there may be more things wrong with this code But I am only interested in getting a basic understanding of password hashing.
$password = mysqli_real_escape_string($con,$password);
You password is now escaped and it certainly won't match the hash.
Better remove this line and look for a better way to ensure the string is safe.
What does escape means?
if your password contains "
it will turns into \"
FYI
Should I mysql_real_escape_string the password entered in the registration form?

Cannot get password_verify to work (PHP, MYSQL)

I've set up password_hash in my registration script. Can't figure out how to use password_verify correctly to log into my website.
Screenshot of DB: https://i.imgur.com/hWjRiXN.png
Login Code (says "incorrect login, even when the password is correct):
<?php
require 'db_connect.php';
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `member` WHERE username='$username'";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if (password_verify($_POST['password'],$hashword))
{
echo "Correct login";
}
else
{
echo "incorrect login";
}
}
?>
Registration Code(Works great, no issues with DB connection either):
<?php
require 'db_connect.php';
$email = $_POST['email'];
$username = $_POST['username'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
if($password1 != $password2)
header('Location: registration.html');
if(strlen($username) > 25)
header('Location: registration.html');
$hashword = password_hash($password,PASSWORD_DEFAULT);
$query = "INSERT INTO member ( username, password, email)
VALUES ( '$username', '$hashword', '$email');";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
mysql_close();
header('Location: login.html');
?>
From your code, it looks like you are not checking the $_POST['password'] with the correct hashword which was inserted into the database.
The variable $hashword will have nothing and hence password_verify fails.
Fetch the value of password which was stored in the database and store it in $hashword variable then use it in the password_verify function for it to work as intended.
Example
$row = mysqli_fetch_assoc($result);
$hashword = $row['password'];
Usage
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
$hashword = $row['password'];
if (password_verify($_POST['password'],$hashword))
{
echo "Correct login";
}
else
{
echo "incorrect login";
}

How to check login in PHP?

i have problem with login , when i entered correct username and wrong password the result should not allow me to login but in my case if the username correct and the password wrong it's allow me to login to the application.
here is my login script
<?PHP
include_once("conn.php");
$user= $_POST['userName'];
$password = mysqli_real_escape_string($_POST['password']);
$qr="select password from user where userName='$user'";
$res=mysqli_query($con, $qr);
while($row=mysqli_fetch_array($res)){
$pass=$row[0];
}
$saltQuery = "select salt from user where userName = '$user'";
$result = mysqli_query($con , $saltQuery);
while($row=mysqli_fetch_array($result)){
$salt = $row[0];
}
$saltedPW = $password . $salt;
$hashedPW = hash('md5', $saltedPW);
if($pass==$hashedPW){
$query = "SELECT userName, password FROM user WHERE userName = '$user' AND password = '$hashedPW'";
$result = mysqli_query($con, $query);
if($result->num_rows > 0){
echo"success login ";
} else{
echo"failed login ";
}
Try to do something that for login page.
<?php
include("config.php");
if(isset($_POST['submit']))
{
echo $username= $_POST['username'];
echo $password= $_POST['password'];
$username = addslashes($username);
$password = addslashes($password);
$username = mysqli_real_escape_string($link, $username);
$password = mysqli_real_escape_string($link, $password);
$pass= md5($password);
$seladmin ="SELECT id,UserName,Password FROM login WHERE UserName='$username' && Password='$pass'";
$SelRecAdmin = mysqli_query( $link,$seladmin );
$row = mysqli_fetch_array($SelRecAdmin);
$tot_num_row=mysqli_num_rows($SelRecAdmin);
if($tot_num_row >0)
{
$_SESSION['adminid']=$row['id'];
$_SESSION['adminunm'] = $row['UserName'];
header('location:home.php');
exit;
}
else
{
$_SESSION['msg']= 'Invalid username or password';
header('location:index.php');
exit;
}
}
?>
I have developed a solution for your question. I didn't run it, if you get any syntax errors kindly fix it by yourself.
**Make sure you don't have same Username in your code, Otherwise it'll show success message if if you enter wrong password. (As per your code ).
But the following code should give you the expected results even if you have multiple entries with same username. **
<?PHP
include_once("conn.php");
$user= $_POST['userName'];
$password = mysqli_real_escape_string($_POST['password']);
$password = hashIt($password,$user);
$res=mysqli_query($con,"select * from user where userName='".$user."' AND password='".$password."'");
if(mysqli_num_rows($res) == 1){
echo "Login Successfull";
}else{
echo "Invalid Username/Password";
}
function hashIt($password,$user){
$result = mysqli_query($con,"select salt from user where userName = '".$user."'");
// No need to check other things, if query fails / no records found anyway it'll show login failure message.
while($row=mysqli_fetch_array($result)){
$salt = $row['salt'];
}
$saltedPW = $password . $salt;
return hash('md5', $saltedPW);
}
?>

password_verify() not verifying

I am trying to verify the hashed password in my database using the password_verify() function but it doesn't seem to be working. Any help please.
<?php
include("config.php");
include("vendor/password.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_real_escape_string($db , $_POST['umail']);
$password = mysqli_real_escape_string($db , $_POST['upassword']);
$userQuery = "SELECT username, password FROM users WHERE username = '$username' AND password='$password'";
$result = mysqli_query($db ,$userQuery);
$queryRow = mysqli_fetch_array($result , MYSQLI_ASSOC);
$queryCount = mysqli_num_rows($result);
$verifyPassowrd = password_verify($_POST['upassword'] , $queryRow[2]);
if ($verifyPassowrd){
header("Location:home.php");
}else{
echo "Username Or Password is invalid";
}
mysqli_close($db);
}
?>
Your password is hashed in your database.
In your query you include a non-hashed password, so the results of the query will be an empty set.
No need to have the password in the WHERE clause of your query, because you want to check the returned hash in the password_verify function.
Updated snippet (I also fixed the typo's):
<?php
include("config.php");
include("vendor/password.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_real_escape_string($db , $_POST['umail']);
$userQuery = "SELECT username, password FROM users WHERE username = '$username'";
$result = mysqli_query($db, $userQuery);
$queryRow = mysqli_fetch_array($result, MYSQLI_ASSOC);
$queryCount = mysqli_num_rows($result);
$verifyPassword = password_verify($_POST['upassword'], $queryRow['password']);
if ($verifyPassword){
header("Location:home.php");
}else{
echo "Username Or Password is invalid";
}
mysqli_close($db);
}
?>

Categories