Cannot get password_verify to work (PHP, MYSQL) - php

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";
}

Related

Storing session variables in PHP loaded from mysqli

I am trying to store session variables upon a login form, so that I can reference them on further pages. The echo of $row[level] is successful, but none of the SESSION variables.
session_start();
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT firstname, level, username FROM `roster` WHERE username ='$username' and password ='$password'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
if ($result->num_rows > 0) {
//while($row = $result->fetch_assoc()) {
//echo $row[level];
//header('location:begin.php');}
while ($row = $result->fetch()) {
$_SESSION['level'] = $row[level];
$_SESSION['firstname'] = $row[firstname];}
}}
I had also tried this, which successfully works for storing the username as a session variable but not the level variable.
session_start();
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT firstname, level, username FROM `roster` WHERE username ='$username' and password ='$password'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$count = mysqli_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
}else{$fmsg = "Invalid Login Credentials.";
}
}if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
$level = $_SESSION['level'];
header ('location: begin.php');
Thanks for your help!
Use quotes here
$_SESSION['level'] = $row["level"];
$_SESSION['firstname'] = $row["firstname"];
Be sure about looping and overwriting variable value, otherwise use array.

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);
}
?>

PHP Log in page with hashed password issue

So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.
<?php
session_start();
include 'databaseconnection.php';
$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);
$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);
if ($hash == 0) {
header("Location: error.php")
exit();
} else {
$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);
if (!row = mysqli_fetch_assoc($result)); {
echo "your email address or password is incorrect!";
} else {
$_SESSION['id'] = $row['id'];
}
header("Location: profile.php")
If someone could simply suggest what changes I should make, I would really appreciate it.
There you go simple code
<?php
session_start();
include 'databaseconnection.php';
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE email = '$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd']; // password from database
// if password is valid start session and redirect to profile.php
if (password_verify($pwd, $hash_pwd))
{
$_SESSION['id'] = $row['id'];
header('Location: profile.php');
}
else
{
header("Location: error.php")
exit();
}
?>
You have not closed the "} else {"... section.
First check request second filter input third use pdo
<?php
session_start();
include 'databaseconnection.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = filter_input(INPUT_POST, 'email',FILTER_VALIDATE_EMAILL); //filter input
$pwd = filter_input(INPUT_POST, 'pwd',FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH); //filter input
$hashed = sha1($pwd);
$sql= $conn->prepare( "SELECT * FROM user WHERE email ? AND password = ?"); //use pdo here
$sql->execute(array($email, $pwd));
$row = $sql->fetch();
if($row['email'] !== $email || $row['password'] !== $hashed){
header("Location: error.php");
exit();
} else {
$_SESSION['id'] = $row['id'];
header("Location: profile.php");
}
}else {
echo 'error';
}
?>

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);
}
?>

password_verify() always return false

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

Categories