How to verify password whith 2 different forms? - php

I have 2 forms : one for Registration and one for Login ([not on the same page, one is a modal][1])
(That's why I did 2 issets at the beginning)
The Registration one is working.
However the Login doesn't work because a User can log in with any password.
I want to verify username/email and of course password. How can I do it ?
Thank you!
Here is my code :
// REGISTRATION
if (isset($_POST['reg_user']) || isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['name']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = "SELECT * FROM utilisateur WHERE pseudoUtil='$username' OR mailUtil='$email'";
$results = mysqli_query($db, $query);
if(mysqli_num_rows($results) == 1){
$_SESSION['message'] = "User already exists !";
}
else{
mysqli_query($db, "INSERT INTO utilisateur (pseudoUtil, mailUtil, pwdUtil) VALUES ('$username', '$email', '$hashed_password')");
$_SESSION['message'] = "Registration complete :)";
}
// LOGIN
if (isset($_POST['login_user'])) {
$query2 = "SELECT $hashed_password FROM utilisateur WHERE pseudoUtil='$username' OR mailUtil='$email'";
$results2 = mysqli_query($db, $query2);
if(mysqli_num_rows($results2) == 1){
$_SESSION['username'] = $username;
header('location: index.php');
}
else{
}
}
}
else{
}
[1]: https://i.stack.imgur.com/fCdAV.png

registration needs to create the password hash and save it to the database, log in needs to pull the hash from the database and compare to the password
both of these tasks should be complete isolated from each other
this means your code should look more like this
note this is an example only not tested as working
POST /register body: username=someone#some.where&password=123456789
function Register(){
$stmt = $mysqli->prepare("SELECT count * as count FROM users WHERE email=?");
$stmt->bind_param("s", $_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if($result->fetch_array(MYSQLI_ASSOC)["count"]>0)
{
return "User already exists"
}
else
{
$hash = password_hash($_POST["password"],PASSWORD_DEFAULT);
$stmt = $mysqli->prepare("INSERT INTO users (username, hash) values (?,?)");
$stmt->bind_param("ss", $_POST["username"], $hash);
$stmt->execute();
$result = $stmt->get_result();
//either return success or set up as a successful login and perform login action
}
}
POST /login body: username=someone#some.where&password=123456789
function Login(){
$stmt = $mysqli->prepare("SELECT hash FROM users WHERE email=?");
$stmt->bind_param("s", $_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if(password_verify($_POST["password"], $result->fetch_array(MYSQLI_ASSOC)["hash"]))
{
//do successful login
}
else
{
//log in failed
}
}

Related

PHP display name of login user

I am trying to display the name of a user when they are logged in. My code uses $_SESSIONS to store the name, but since there no input in my login in page, the name doesn't get assign and it ends up being just hello, instead of something like hello, John Smith.
I've tried using sql to select the name by matching the email to the email of the logged in user, and storing that in $_SESSION but it still doesn't print name of user.
my server.php
<?php
include_once "inc/user-connection.php";
session_start();
$name = mysqli_real_escape_string($conn, $_POST['name']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$username = mysqli_real_escape_string($conn, $_POST['username']);
if (isset($_POST['admin-sign-in'])) {
if (!empty($email)) {
if (!empty($password)) {
$sql = 'SELECT email, password FROM admin WHERE email = ?';
// preparing the SQL statement
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$stmt->store_result(); // Store the result so we can check if the account exists in the database.
// If email exists in sign_up table
if ($stmt->num_rows > 0) {
$stmt->bind_result($email, $password);
$stmt->fetch();
// if password user enters matches the one in the database
if (password_verify($password, $hashed_password)) {
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$_SESSION['name'] = $row['name'];
// upon successful login, redirect user to landing apge
header("location: dashboard.php");
die();
} else {
// Incorrect password
header("location: ../html/sign-in-error.html");
die();
}
} else {
// Incorrect username
header("location: ../html/sign-in-error.html");
die();
}
$stmt->close();
}
} else {
header("location: ../html/404-error.html");
die();
}
} else {
header("location: ../html/404-error.html");
die();
}
}
my dashboard.php
<?php
session_start();
?>
<div class="d-block">
<h1 class="lead fw-normal text-muted mb-4 px-lg-10">Hello,
<?php
echo $_SESSION['name'];
?>
</h1>
</div>
You did not select the name and you are fetching it.
$sql = 'SELECT email, password, name FROM admin WHERE email = ?';
or
$sql = 'SELECT * FROM admin WHERE email = ?';
should fix the issue.
Additional: you can remove all your else statements since all of it will give the same result.
<?php
include_once "inc/user-connection.php";
session_start();
$name = $_POST['name'];
$password = $_POST['password'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$email = $_POST['email'];
$username = $_POST['username'];
if (isset($_POST['admin-sign-in'])) {
if (!empty($email)) {
if (!empty($password)) {
$sql = 'SELECT * FROM admin WHERE email = ?';
// preparing the SQL statement
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$stmt->store_result(); // Store the result so we can check if the account exists in the database.
// If email exists in sign_up table
if ($stmt->num_rows > 0) {
$stmt->bind_result($email, $password, $name);
$stmt->fetch();
// if password user enters matches the one in the database
if (password_verify($password, $hashed_password)) {
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$_SESSION['name'] = $row['name'];
// upon successful login, redirect user to landing apge
header("location: dashboard.php");
die();
}
}
$stmt->close();
}
}
}
header("location: ../html/404-error.html");
die();
}

Login page keeps showing error PHP and MySQL

I am having issues getting some simple (or it seems simple) coding to cooperate. I've tried stripping it completely and typing everything out. Here is the code:
<?php
session_start();
if(isset($_POST['login'])) {
$username = trim($_POST['username']);
$password = md5(trim($_POST['password']));
include('includes/admin.php');
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) == 0) {
echo '<p>Incorrect login.<br>Return to Login Page</p>';
} else {
$_SESSION['user'] = $username;
echo '<p>Login successful.<br>Go to Admin Page</p>';
}
}
?>
The goal is to have it redirect to the login page if unsuccessful and to redirect to another admin page if successful. I keep getting the "Incorrect Login" error, even when I type in the correct username and password.
Side Note: I know to redirect, I need to use header('Location: link.php'), it is not included for testing purposes.
If you didn't save your password as MD5 hash in your database you will never match it, cause in the line above you hash the password via MD5 before using in the query.
MD5 isn't secure! Use the PHP internal functions (password_hash(), password_verify()) to create and check passwords!
Use prepared statements!
Example code:
<?php
// Save a new user password in DB
$username = 'Max User';
$password = 'My_Secr3t_Pa5sw0rd';
$passwordHash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare("INSERT INTO `users` (`username`, `password`) VALUES(?, ?)");
$stmt->bind_param("ss", $username, $passwordHash);
$stmt->execute();
// Check user password
$stmt = $mysqli->prepare("SELECT `password` FROM `users` WHERE `username`=?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if (password_verify($password, $row['password']) {
echo "Password correct";
} else {
echo "Password incorrect!";
}
?>

Unable to extract password hash from database with prepared statements

EDIT: To clarify, I am unable to extract the hashed password from my database using prepared statements.
I'm trying to create a login system that uses prepared statements, password_hash and password_verify.
I have created the registering form that creates the user, with the hashed password using password_hash($_POST['password'], PASSWORD_DEFAULT);
This works properly.
However, I am now stuck on creating the login form.
I am trying to get the password hash that gets stored when a user registers but I cannot get it to work with prepared statements.
This is what I currently have.
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
}
}
?>
How do I use the data that I got from the select query? And how do I use it to verify the password?
I tried:
$stmt->store_result();
$stmt->bind_result($loginUsername, $hash);
That only stored the username, but not the password hash and I have no clue why.
Verifying the password would use this?
password_verify($password, $hash);
UPDATE
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
// Get query results
$result = $stmt->get_result();
// Fetch the query results in a row
while($row = $result->fetch_assoc()) {
$hash = $row['user_password'];
$username = $row['user_name'];
}
// Verify user's password $password being input and $hash being the stored hash
if(password_verify($password, $hash)) {
// Password is correct
} else {
// Password is incorrect
}
}
}
?>
Read this PHP MANUAL.Try this:
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
// Get query results
$stmt->bind_result($user_name,$hash);
$stmt->store_result();
// Fetch the query results in a row
$stmt->fetch();
// Verify user's password $password being input and $hash being the stored hash
if(password_verify($password, $hash)) {
// Password is correct
} else {
// Password is incorrect
}
}
}
?>
This is how I created my login system:
$stmt = mysqli_prepare($link,"SELECT user_email,user_password,user_firstname,user_lastname,user_role,username FROM users WHERE user_email=?");
mysqli_stmt_bind_param($stmt,"s",$email);
mysqli_stmt_execute($stmt);
confirmQuery($stmt);
mysqli_stmt_bind_result($stmt,$user_email,$user_password,$user_firstname,$user_lastname,$user_role,$username);
mysqli_stmt_store_result($stmt);
mysqli_stmt_fetch($stmt);
if(mysqli_stmt_num_rows($stmt) == 0)
relocate("../index.php?auth_error=l1");
else{
if(password_verify($password,$user_password)){
$_SESSION['userid'] = $user_email;
$_SESSION['username'] = $username;
$_SESSION['firstname'] = $user_firstname;
$_SESSION['lastname'] = $user_lastname;
$_SESSION['role'] = $user_role;
if(isset($_POST['stay-logged-in']))
setcookie("userid", $email, time() + (86400 * 30), "/");
relocate("../index.php?auth_success=1");
}else
relocate("../index.php?auth_error=l2");
}
mysqli_stmt_close($stmt);

Login user using password_verify

I'm creating a back end to my website and running into issues with the login user part.
The user registration into the database is made with the password_hash function using the code below:
UserReg.php :
<?php
require_once 'db.php';
$mysqli = new mysqli($host, $user, $password, $dbname);
if($mysqli -> connect_error) {
die($mysqli -> connect_erro);
}
$username = "userF";
$password = "somePass";
$token = password_hash("$password", PASSWORD_DEFAULT);
add_user($mysqli,$username, $token);
function add_user($mysqli,$username, $token) {
$query = $mysqli->prepare("INSERT INTO users(username, password) VALUES
(?,?)");
$query->bind_param('ss',$username, $token);
$query->execute();
$result = $query->get_result();
if(!$result) {
die($mysqli->error);
}
$query->close();
}
My login form skips to a blank page even when i insert my username and password. Doesn't even go to the login error message.
Login.php
<?php
include 'db.php';
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$stmt->bind_result($pass);
while ($result = $stmt->num_rows()) {
if($stmt->password_verify($pwd, $result)) {
echo "Your username or password is incorrect";
} else {
header("Location: Menu.php");
}
}
What am i missing?
Appreciate your help.
I think you need to take a look at password_verify how it works.
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT username, password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if ($stmt->num_rows == 1) { //To check if the row exists
if ($stmt->fetch()) { //fetching the contents of the row
if (password_verify($pwd, $password)) {
$_SESSION['username'] = $username;
echo 'Success!';
exit();
} else {
echo "INVALID PASSWORD!";
}
}
} else {
echo "INVALID USERNAME";
}
$stmt->close();

Having trouble with PDO queries

Can someone please take a look at this block of code? I am very new to the PDO method, for some reason this keeps causing a 500 error whenever I submit.
I have narrowed it down to this:
Could it be this part? $hash = $stmt['hash'];
if(empty($response['error'])){
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
$hash = $stmt['hash'];
$affectedRows = $stmt->rowCount(); // Getting affected rows count
if($affectedRows != 1){
$response['error'][] = "No User is related to the Username";
}
if(password_verify($password, $hash))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $stmt['ID'];
}
else
{
$response['error'][] = "Your password is invalid.";
}
}
If you need more info please ask I will be happy to supply anything I can.
You need to fetch the result of the query to have it accessible. I'm not sure this is your issue, I'd think $hash would just be set to Resource Id#x, not what you want but not a 500. Here's how to fetch (http://php.net/manual/en/pdostatement.fetch.php) though
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
//if you will only be getting back one result you dont need the while or hashes as an array
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
$hashes[] = $result['hash'];
}
Here's a thread on enabling error reporting PHP production server - turn on error messages
Also you don't have to bind to pass values with the PDO. You also could do
$stmt = $db->prepare("SELECT * FROM Login WHERE username= ?"); // Prepare the query
$stmt->execute(array($username));
Your code is really messy. Just to help you with start point:
if (empty($response['error'])) {
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$hash = $row['hash'];
if(password_verify($password, $hash)) {
$_SESSION['username'] = $username;
$_SESSION['userid'] = $stmt['ID'];
} else {
$response['error'][] = "Your password is invalid.";
}
} else {
$response['error'][] = "No User is related to the Username";
}
} else {
$response['error'][] = "Username is not set!";
}
}

Categories