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);
}
?>
Related
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.
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";
}
I've put username and md5(password) on my MySQL database. Below is my old login PHP code. I want to add some code that can retrieve my md5 password, because on my old code there is no md5 password. Where is should I add md5(password)?
Here is my full login code:
<?
if ($_POST['username']) {
$username=trim($_POST['username']);
$username = mysql_real_escape_string($username);
$password=trim($_POST['password']);
$password=mysql_real_escape_string($password);
//$password = hash('md5','$password');
if ($password==NULL) {
header("Location: login.php?error=2");
}else{
if($_POST['code']!=$_SESSION['string']){
header("Location: login.php?error=1");
}else{
$query = mysql_query("SELECT username,password FROM tb_users WHERE username = '$username'") or die(mysql_error());
if(mysql_num_rows($query) == 0)
{
header("Location: login.php?error=3");
} else {
$data = mysql_fetch_array($query);
if($data['password'] != $password) {
header("Location: login.php?error=4");
}else{
$query = mysql_query("SELECT username,password FROM tb_users WHERE username='$username' ") or die(mysql_error());
$row = mysql_fetch_array($query);
$nicke=$row['username'];
$passe=$row['password'];
setcookie("usNick",$nicke,time()+36000);
setcookie("usPass",$passe,time()+36000);
$lastlogdate=time();
$lastip = getRealIP();
$querybt = "UPDATE tb_users SET lastlogdate='$lastlogdate', lastiplog='$lastip' WHERE username='$nicke'";
mysql_query($querybt) or die(mysql_error());
$query = mysql_query("SELECT akhirupgrade from tb_upgrade WHERE username = '$username' and status='upgraded'") or die(mysql_error());
if(mysql_num_rows($query) > 0) {
$row = mysql_fetch_array($query);
$akhir=$row["akhirupgrade"];
$tgl=time();
if ($tgl > $akhir) {
$query = mysql_query("update tb_upgrade set status='', date='', paket='', akhirupgrade='' WHERE username='$username' and status='upgraded'");
$query = mysql_query("update tb_users set account='' WHERE username='$username'");
}
}
header("Location: member.php");
}
}
}
}
}
?>
I would use password_hash() if you running on php 5.5 or greater
When you send the password to the database simply hash it with the function
$password = password_hash(filter_input(INPUT_POST, "password"));
The when you pull the password back out of the database do the same thing to the password they submitted.
$passwordFromDb = $result['password']; //Password from the database
$passwordFromLoginForm = password_hash(filter_input(INPUT_POST, "password");
//Then when youve got the password to check it agaisnt there input
if($passwordFromDb === $passwordFromForm){
//The password they entered was the same as the password in the database
} else {
//The password was wrong
}
I have not tested this code so there may be errors but hopefully youll get the point :)
PS dont use MD5 please, Very insecure
If you must use md5
$password = md5(filter_input(INPUT_POST, "password"));//Store password
$passwordFromDb = $result['password']; //Password from the database
$passwordFromLoginForm = md5(filter_input(INPUT_POST, "password");
//Then when youve got the password to check it agaisnt there input
if($passwordFromDb === $passwordFromForm){
//The password they entered was the same as the password in the database
} else {
//The password was wrong
}
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);
}
?>
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