password_verify stops working after changing hash - php

I'm working on implementing the ability for users to edit their passwords.
I'm using PASSWORD_BYCRYPT, and password_verify works fine after creating a user, but as soon as a user edits their password, it stops working.
Password change:
else if (isset($_POST["submitUpdateSettingsPW"])) {
$passwordText = $_POST["passwordChangeInput"];
$userID = $_SESSION["userID"];
$passwordNew = password_hash($passwordText, PASSWORD_BCRYPT);
$sql = "UPDATE users SET password = '$passwordNew' WHERE id = '$userID';";
if (mysqli_query($conn, $sql)) {
header("location: settings.php");
}
else {
header("location: settings.php?message=Something+went+wrong.+You+may+not+have+the+permissions+to+do+this.");
}
}
Password creation
else if (isset($_POST["submitSignup"])) {
$email = mysqli_real_escape_string($conn, $_POST["emailInput"]);
$passwordText = $_POST["passwordInput"];
$password = password_hash($passwordText, PASSWORD_BCRYPT);
$signupSQLCheck = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($conn, $signupSQLCheck);
if (mysqli_num_rows($result) == 0) {
$signupSQL = "INSERT INTO users set email = '$email', password = '$password'";
mysqli_query($conn, $signupSQL);
header("location: login.php?message=Your+account+is+active.+You+may+now+login.");
}
else {
header("location: login.php?message=This+email+is+already+registered.+Do+you+want+to+<a href = 'login.php'>login</a>?");
}
}
Password verify (works fine until changing password)
if (isset($_POST["submitLogin"])) {
$email = mysqli_real_escape_string($conn, $_POST["emailInput"]);
$passwordText = $_POST["passwordInput"];
$loginSQL = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$result = mysqli_query($conn, $loginSQL);
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
$hash = $row["password"];
if (password_verify($passwordText, $hash)) {
$_SESSION["user"] = 1;
$_SESSION["userID"] = $row["id"];
header("location: index.php");
}
}
else {
header("location: login.php?message=Incorrect+email+or+password.+Do+you+want+to+<a href = 'signup.php'>sign up</a>?");
}
}
Thanks in advance

Related

Checking if users exists

I did a lot of googling and tried many methods but checking for username existence in Mysqli database is not working. Everything is correct but still the user is getting registered even if there is a username in Database. Please help...My php version is 7 and phpmyadmin is 5.6. My code :-
<?php
session_start();
if (isset($_SESSION['id'])) {
header('Location: user.php');
die();
}
else {
if($_POST['submit']){
$username = strip_tags($_POST['username']);
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
$passhash = hash('sha512', $password);
$passhash2 = hash('sha512', $passhash);
$strlen = strlen("$password");
if ($strlen < 10) { {
$lesspass = "Use password of atleast 10 letters";
}
}
else {
$date = date("Y-m-d");
require ('setup.php');
$conn = new mysqli($localhost, $hostuser, $hostpass, $hostdb) or die("conn died");
$query1 = "SELECT * FROM member WHERE username = '$username'";
$result1 = mysqli_query($conn, $query1);
if (mysqli_num_rows($query1) > 0) {
die ("Username in use");
}
else {
$query2 = "SELECT from member WHERE email = $email";
$result2 = mysqli_query($conn, $query2);
if (($result2) > 0) {
$ee = "Email already exists";
}
else {
$query = "INSERT INTO member(username, password, registered, email, activated, status) VALUES('$username', '$passhash2', '$date', '$email', '1', '0')";
$result = mysqli_query($conn, $query);
if($result) {
header('Location: login.php');
}
else {
echo "There was a problem while connecting";
}
}
}
}
}
}
?>
I think the error is that you use mysqli_num_rows on the query string. Do it on the result:
if (mysqli_num_rows($result1) > 0) {
Also, you should take care about SQL injections (escape or use prepared statements), but that's another story. Not sure if strip_tags is sufficient.

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() 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

If else statement error confused

Hello guys I was confused using the if else statement I know it is the basic in conditioning also other languages. Don't know what to do here, I would like that it has an if condition(check) then also inside I want that it has an else if but my problem is I have to else statement which is wrong cause I know that else statement will be use at the end of a condition
Here's my code:
if (isset($_POST['login']))
{
$idno = mysql_real_escape_string($_POST['idno']);
$password = mysql_real_escape_string($_POST['password']);
$position = $_POST['user_type'];
$YearNow=Date('Y');
$_SESSION['SESS_MEMBER_ID'] = $idno;
$sql1 = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password' " ;
$result = mysql_query($sql1) or die();
$row = mysql_fetch_array($result);
$num_row = mysql_num_rows($result);
//,student WHERE studentvotes.idno = student.idno
$sql2 = "SELECT * FROM vote_logs,school_year where vote_logs.idno='$idno' AND vote_logs.syearid = school_year.syearid AND school_year.from_year like $YearNow ";
$result1 = mysql_query($sql2) or die();
$row1 = mysql_fetch_array($result1);
if (mysql_num_rows($result1)<=1)
{
$_SESSION['idno']=$row['idno'];
$sql_c = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password'";
$result2 = mysql_query($sql_c) or die(mysql_error());
$faunc = mysql_fetch_assoc($result2);
$_SESSION['SESS_COURSE'] = $faunc['progid'];
$_SESSION['SESS_MEMBER_ID'] = $idno;
header('location: plsvote.php');
}
else if ($row['status'] == 'lock')
{
header('location: last.php');
}
else
{
header('location: notification.php');
exit();
}
else
{
echo "<script type='text/javascript'>\n";
echo "alert('Username or Password incorrect!, Please try again.');\n";
echo "window.location = 'index.php';";
echo "</script>";
exit();
}
}
Please help me
You have imbricated your blocks, try this:
if (isset($_POST['login']))
{
$idno = mysql_real_escape_string($_POST['idno']);
$password = mysql_real_escape_string($_POST['password']);
$position = $_POST['user_type'];
$YearNow=Date('Y');
$_SESSION['SESS_MEMBER_ID'] = $idno;
$sql1 = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password' " ;
$result = mysql_query($sql1) or die();
$row = mysql_fetch_array($result);
$num_row = mysql_num_rows($result);
//,student WHERE studentvotes.idno = student.idno
$sql2 = "SELECT * FROM vote_logs,school_year where vote_logs.idno='$idno' AND vote_logs.syearid = school_year.syearid AND school_year.from_year like $YearNow ";
$result1 = mysql_query($sql2) or die();
$row1 = mysql_fetch_array($result1);
if (mysql_num_rows($result1)<=1)
{
$_SESSION['idno']=$row['idno'];
$sql_c = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password'";
$result2 = mysql_query($sql_c) or die(mysql_error());
$faunc = mysql_fetch_assoc($result2);
$_SESSION['SESS_COURSE'] = $faunc['progid'];
$_SESSION['SESS_MEMBER_ID'] = $idno;
header('location: plsvote.php');
}
else if ($row['status'] == 'lock')
{
header('location: last.php');
}
else
{
header('location: notification.php');
exit();
}
}
else
{
echo "<script type='text/javascript'>\n";
echo "alert('Username or Password incorrect!, Please try again.');\n";
echo "window.location = 'index.php';";
echo "</script>";
exit();
}
With an indentation, this kind of problem is easily visible.
This can be ok:
if ( //validate the email
filter_var($email, FILTER_VALIDATE_EMAIL) &&
preg_match('/#.+\./', $email)
) {
$result = mysql_query (
"INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())"
);
if ($result) { // check for successful store
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false; //unsuccessful store
}
} else {
//not a valid email
return false;
}
}
Try this one :
if (filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/#.+\./', $email)) {
$result = mysql_query ("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
if ($result) { // check for successful store
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false; //unsuccessful store
}
} else {
//not a valid email
return false;
}

PHP Login Using password_hash

The following code does not work:
Login Page:
if (isset($_POST['login'])) {
$name = $mysqli->real_escape_string($_POST['name']);
$pass = $_POST['pass'];
$query = "SELECT * FROM users WHERE name='{$name}'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if(password_verify($pass, $row['pass'])){
$_SESSION['logged'] = true;
$_SESSION['name'] = $row['name'];
$_SESSION['pass'] = $row['pass'];
//header('Location: index.php');
echo "Workded";
} else {
echo "Crypt Not Matching";
}
}
}
}
Code used to insert into database:
if (empty($e1)) {
$password = password_hash($pass, PASSWORD_BCRYPT);
if ($mysqli->query("INSERT into users (name, pass, email, gamertag, psnid, youtube, fbauth) VALUES ('$username', '$password', '$email', '$xbox', '$psn', '$youtube', '$fbid')")) {
session_start();
$_SESSION['logged'] = true;
$_SESSION['name'] = $username;
$_SESSION['pass'] = $password;
header('Location: index.php');
}
}
Can anyone point out what I'm doing wrong?
1 - debug the $_POST var and check if its being passed correctly from the HTTP POST request
var_dump($_POST);
2 - debug the result of the database, in the foreach loop, and check if you're retrieving the information from the db correctly
while($row = $result->fetch_assoc()) {
var_dump($row);
}
3 - test if password_hash and password_verify are working correctly.
$pwd = 'some_password';
$hash = password_hash($pwd, PASSWORD_BCRYPT);
var_dump(password_verify($pwd, $hash);

Categories