Password always wrong using password_verify with database - php

I'm using password_verify with database when I login it always say password incorrect and in my database I'm using char 255 for password.
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
$userrecord1 = mysqli_query($db, "SELECT * FROM users WHERE username='$_POST[username]' LIMIT 1");
if (count($userrecord1) == 1 ) {
$urow1 = mysqli_fetch_array($userrecord1);
$hash = $urow1["password"];
}
// attempt login if no errors on form
if (count($errors) == 0) {
$passuser = password_verify($password, $hash);
$query = "SELECT * FROM users WHERE (username='$username' OR email='$username') AND password='$passuser' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "Welcome admin";
header('location: /admin/home');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "Welcome user";
header('location: /home/index');
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}

There's a few things I'd like to note,
Usage of the global keyword is not recommended - you should instead pass values as arguments to the function instead.
You are wide open to SQL injection - use a prepared statement
Once you have verified the password by password_verify(), the password is correct and the user has verified his login.
if (count($userrecord1) == 1 ) { doesn't make much sense, as you haven't fetched any records yet.
Your second select is moot (see point 3), and invalid as selecting from a hashed password will not yield the result.
Use exit; after header("Location: .."); calls
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
$stmt = $db->prepare("SELECT password, user_type FROM users WHERE username=? LIMIT 1");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($dbPassword, $userType);
if ($stmt->fetch() && password_verify($password, $dbPassword)) {
if ($userType == 'admin') {
$_SESSION['user'] = $username;
$_SESSION['success'] = "Welcome admin";
header('location: /admin/home');
exit;
} else {
$_SESSION['user'] = $username;
$_SESSION['success'] = "Welcome user";
header('location: /home/index');
exit;
}
} else {
$errors[] = "Wrong username/password combination";
}
}

Related

How to use the encrypt password for login php [duplicate]

This question already has answers here:
How to use PHP's password_hash to hash and verify passwords
(5 answers)
Closed 1 year ago.
At first I am using md5 for hashing but then I learn that password_hash is more secured, but when I tried to use it in my website it wont work. I've tried putting the code password_verify everywhere.
When I'm trying to login it just giving me an error of password/ email combination is wrong even if it is correct. I also get the error for the password verify but when I put the correct credentials it's still giving me the error message
This is my login code
<?php
function login(){
global $db, $email, $errors;
// grab form values
$email = e($_POST['email']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($email)) {
array_push($errors, "Email is required");
}else {
$email = hsc($_POST["email"]);
}
if (empty($password)) {
array_push($errors, "Password is required");
}else{
$password = hsc($_POST["password"]);
}
// attempt login if no errors on form
if (count($errors) == 0) {
$query = "SELECT * FROM accounts WHERE email='$email' AND password='$password' LIMIT 1";
$results = mysqli_query($db, $query);
if (password_verify($password, $_POST["password"])) {
array_push($errors, "Wrong password");
}
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: admin/admin.php');
exit(0);
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
exit(0);
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
This is my register code (There are all in the same file functions.inc.php)
function register(){
// call these variables with the global keyword to make them available in function
global $db, $errors, $username, $email;
// receive all input values from the form. Call the e() function
// defined below to escape form values
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password']);
$password_2 = e($_POST['re-password']);
//check email if already exist on database
$check = "SELECT * FROM accounts WHERE email='$email'";
$res_e = mysqli_query($db, $check);
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Name is required");
}elseif (!preg_match("/^[a-zA-Z]+( [a-zA-Z]+)*$/",$username)) {
array_push($errors, "Only letters and one space only");
}else{
$username = hsc($_POST["username"]);
}
if (empty($email)) {
array_push($errors, "Email is required");
}elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
array_push($errors, "The email is invalid");
}elseif (mysqli_num_rows($res_e) > 0) {
array_push($errors, "The email already taken");
}else{
$email = hsc($_POST["email"]);
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}elseif ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}else{
$password_1 = hsc($_POST["password_1"]);
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$hashpassword = password_hash($password_1, PASSWORD_DEFAULT);;//encrypt the password before
saving in the database
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO accounts (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$hashpassword')";
mysqli_query($db, $query);
$_SESSION['add'] = "Added successfully";
header('location: users.php');
exit(0);
}else{
$query = "INSERT INTO accounts (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$hashpassword')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['add'] = "You are now logged in and thank you!";
header('location: index.php');
exit(0);
}
}
}
I don't know if this is also the reason that the login is not working but it is better that I put it in. This is the code for function hsc() and e()
// escape string
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
// htmlspecialchars the inputs data
function hsc($val) {
$val = htmlspecialchars($val);
return $val;
}
Here is the data base photo
(By far the simplest method...)
Try this example. It uses Argon2, which is by far the safest encryption method (AFAIK)
Note that it randomly generates a different string when run, so using password_verify is mandatory unlike using sha-256 to look up the password in the database
<?php
$pwd = password_hash("my password goes here", PASSWORD_ARGON2I);
// Use $_POST instead
echo $pwd;
?>
And to verify your password:
if(password_verify($_POST['password'], $row["password"])) {
// Your code here...
}
Also, use PDP PDO, it's much safer against SQL injection attacks
<?php
$db = new PDO('mysql:host='.$servername.';dbname='.$dbname.';charset=utf8mb4', $username, $password);
try {
$query = "SELECT * from `login` WHERE `username`=:username OR `email` =:usernamea";
$stmt = $db->prepare($query);
$stmt->bindParam('username', $username, PDO::PARAM_STR);
$stmt->bindParam('usernamea', $username, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($count == 1 && !empty($row)) {
$auth_email = $row['email'];
$auth_pwd = $row['password'];
if(password_verify($_POST['password'], $auth_pwd)) {
$validuser = $row['username'];
$_SESSION['valid'] = $validuser;
$_SESSION['name'] = htmlspecialchars($row['name']);
}
else {
echo 'Invalid';
}
}
else {
echo 'Invalid';
}
}
catch (PDOException $e) { echo "Error : ".$e->getMessage(); }
?>

How to echo from database in session?

I have problem with PHP $_SESSION.
I see only "username" in index page after successfull login/register.
When I change $_SESSION['username'] to $_SESSION['password'] is also displayed.
I need to display "points" value, which is not defined by user during login/register (5 points is auto added to user after register)
How to echo values from database, which are not inserted by users?
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Please write username");
}
if (empty($password)) {
array_push($errors, "Please write password");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "Logged in ";
header('location: index.php');
}else {
array_push($errors, "Something went wrong");
}
}
}```
Try with :
...
if (mysqli_num_rows($results) == 1) {
$row=mysqli_fetch_assoc($result);
//check the data you get from the BD
var_dump($row);die;
// you'll get an array with you data where you'll find the points
// then just assign it to a session
$_SESSION['user_points'] = $row['user_points']; // for example
$_SESSION['username'] = $username;
$_SESSION['success'] = "Logged in ";
header('location: index.php');
}
...

password_verify for hashed password

I have admin page that will insert user id, password, role. The password will be hash after admin insert new user. It work well but when I try to login using the hash password, it will pop up "invalid user or password". Maybe because I put the password_verify coding in the wrong place. Can someone help me!!
Below is my coding
login.php
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "","company");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query($connection, "select * from login where password='$password' AND username='$username'");
$row=mysqli_fetch_assoc($query);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$pwdCheck = password_verify($password,$row['password']); $_SESSION['user']=array(
'username'=>$row['username'],
'password'=>$row['password'],
'role'=>$row['role']
);
$role=$_SESSION['user']['role'];
//Redirecting User Based on Role
switch($role){
case 'user':
if ($pwdCheck == true)
header("location: index.php"); // Redirecting To Other Page
break;
case 'admin':
if ($pwdCheck == true)
header("location: adminindex.php"); // Redirecting To Other Page
break;
}
}
else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
?>
crud_include.php (admin insert new user)
if (isset($_POST['save'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$role = $_POST['role'];
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_query($db, "INSERT INTO login (username, password,role) VALUES ('$username', '$hashedPwd','$role')");
$_SESSION['message'] = "Successfully saved!";
header('location: crud.php');
}
the database (the hash work well but i cannot login using this user
Change your select query : In a where case use only username
<?php
$username=$_POST['username'];
$password=$_POST['password'];
$query = mysqli_query($connection, "select * from login WHERE username='$username'");
$row=mysqli_fetch_assoc($query);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
if (password_verify($password, $row['password'])) {
echo 'Password is valid!';
if($role=$_SESSION['user']['role'] == 'user'){
header("location: index.php");
}elseif($role=$_SESSION['user']['role'] == 'admin'){
header("location: adminindex.php");
}
} else {
$error = "Password is invalid";
}
}else{
$error = "Username is invalid";
}
?>
Hope it will help you.
Here the the link for the hash password verified

Login not functioning with converted Prepared Statements SQLi

As recommended, I've been trying to secure my DB by using prepared statements. I have the following login that works perfectly that I'm trying to convert to prepared statement.
if(isset($_POST["Submit"])) {
$Username = mysqli_real_escape_string($con, $_POST["Username"]);
$get_hash_db = mysqli_query($con, "SELECT password FROM admin_registration WHERE username='$Username'");
$hash_db_data = mysqli_fetch_array($get_hash_db);
$hash = $hash_db_data['password'];
echo $hash;
if(password_verify($_POST['Password'], $hash)){
$Password = $hash;
}else {
$_SESSION["ErrorMessage"] = "Username or Password was incorrect";
Redirect_to("admin_login.php");
}
else {
$Found_Account = Login_Attempt($Username, $Password);
$_SESSION["User_Id"] = $Found_Account["id"];
$_SESSION["Username"] = $Found_Account["username"];
if($Found_Account) {
$_SESSION["SuccessMessage"] = "Login Successful! Welcome {$_SESSION["Username"]}";
Redirect_to("blog_admin/dashboard.php");
}else {
$_SESSION["ErrorMessage"] = "Invalid Username / Password";
Redirect_to("admin_login.php");
}
}
}
Below this it takes you into a Login_Attempt() function that look like this:
function Login_Attempt($Username, $Password) {
global $con;
$sql = "SELECT * FROM admin_registration WHERE username='$Username' AND password='$Password'";
$result = mysqli_query($con, $sql);
if($admin = mysqli_fetch_assoc($result)) {
return $admin;
}
else {
return null;
}
}
With my new prepared statements I never get past $_SESSION["ErrorMessage"] = "Invalid Username / Password"; Which tells me that I'm at least satisfying the condition $Password = $hash; Here is what I have.
if(isset($_POST["Submit"])) {
$Username = mysqli_real_escape_string($con, $_POST["Username"]);
$get_hash_db = mysqli_prepare($con, "SELECT password FROM admin_registration WHERE username = ? ");
mysqli_stmt_bind_param($get_hash_db, "s", $Username);
mysqli_stmt_execute($get_hash_db);
mysqli_stmt_bind_result($get_hash_db, $hash);
mysqli_stmt_fetch($get_hash_db);
echo $hash;
if(password_verify($_POST['Password'], $hash)){
$Password = $hash;
}else {
$_SESSION["ErrorMessage"] = "Username or Password was incorrect";
Redirect_to("admin_login.php");
}
Once I get passed this, I'm going through this:
else {
$Found_Account = Login_Attempt($Username, $Password);
$_SESSION["User_Id"] = $Found_Account["id"];
$_SESSION["Username"] = $Found_Account["username"];
if($Found_Account) {
$_SESSION["SuccessMessage"] = "Login Successful! Welcome {$_SESSION["Username"]}";
Redirect_to("blog_admin/dashboard.php");
}else {
$_SESSION["ErrorMessage"] = "Invalid Username / Password";
Redirect_to("admin_login.php");
}
}
}
but it always returns to $_SESSION["ErrorMessage"] = "Invalid Username / Password"; I'm not sure I understand why? Is it because I'm binding the param $Username, so function Login_Attempt($Username, $Password) does not handle correctly? Sorry, this is my first go at prepared statements so really struggling to understand.

Create session using retrieved data

I have a login page where user insert their username and password.
I create a session which will display the username of the user at the main page using below code.
However, instead of the username, I want to display the user's full name. How do I display the full name using $_SESSION['username']?
My table name is users and consist of column fullname, username and password.
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
Use db query like mysqli_fetch_assoc to get data from db
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$row = mysqli_fetch_assoc($results );
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
for more : https://www.w3schools.com/php/func_mysqli_fetch_row.asp

Categories