How to take and verify hashed password from db [duplicate] - php

This question already has answers here:
Password is not verified using function password_verify
(4 answers)
Closed 6 years ago.
In my register.php i use this code to make hashed password:
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
And i want to verify password hash in db but i dont know how to use password_verify correctly. Here is my login.php script to login
login.php
<?php
include('Global/global.inc.php');
if(isset($_SESSION['user_name'])!='') {
header("Location: index.php");
}
include('Global/view/view.login.php');
//check if form is submitted
if (isset($_POST['signin'])) {
$user_name = mysqli_real_escape_string($connect, htmlspecialchars($_POST['user_name']));
$user_pass = mysqli_real_escape_string($connect, htmlspecialchars($_POST['user_pass']));
$result = mysqli_query($connect, "SELECT * FROM `" . USERS_TABLE . "` WHERE user_name = '$user_name' AND user_pass = '$user_pass'");
if (empty($user_name) || empty($user_pass)) {
echo "empty fields";
}
if ($row = mysqli_fetch_array($result)) {
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_avatar'] = $row['user_avatar'];
$_SESSION['user_mail'] = $row['user_mail'];
header("Location: index.php");
}
else {
echo 'Invalid Username or Password!<br />';
}
}

from the manual http://php.net/manual/en/function.isset.php
isset — Determine if a variable is set and is not NULL
isset() returns bool true or false you should only have
if (isset($_SESSION['username']))
use password_verify();
http://php.net/manual/en/function.password-verify.php
example
<?php
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify($password, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>

i edited your code and added some comments to make it clear hope it helps
if( isset($_SESSION['user_name']) ) {
header("Location: index.php");
}
include('Global/view/view.login.php');
//check if form is submitted
if (isset($_POST['signin'])) {
$user_name = mysqli_real_escape_string($connect, htmlspecialchars(trim($_POST['user_name'])));
$user_pass = trim($_POST['password']); // trim deletes spaces from left and right password doesn't need sanitization
//check fields
if (empty($user_pass) || empty ($user_name) ) {
echo "empty fields";
}
elseif ($result = mysqli_query($connect,$sql)){
// check username if it exists procceds to password checking
if (mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$hashedpassword = $row["password"];
//check password if username exists
if (password_verify($password, $hashedpassword))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_avatar'] = $row['user_avatar'];
$_SESSION['user_mail'] = $row['user_mail'];
header("Location: index.php");
}
} else {
echo 'Invalid Username or Password!<br />';
} } else {
echo 'Invalid Username or Password!<br />';
}
}

If you want to check the login password with the DB hashed password, then convert the login password to hash and compare them both. That is:
$user_pass = password_hash($user_pass, PASSWORD_DEFAULT);
$result = mysqli_query($connect, "SELECT * FROM `" . USERS_TABLE . "` WHERE user_name = '$user_name' AND user_pass = '$user_pass'");
if (empty($user_name) || empty($user_pass)) {
echo "empty fields";
}
if ($row = mysqli_fetch_array($result)) {
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_avatar'] = $row['user_avatar'];
$_SESSION['user_mail'] = $row['user_mail'];
header("Location: index.php");
}
else {
echo 'Invalid Username or Password!<br />';
}
}

Related

entering any password still logs in

I am entering any password but I am getting successful logins. I am confused.
php code:
// LOGIN USER
// variable declaration
$email = "";
$mobile = "";
$under_userid = "";
$errors = array();
$_SESSION['success'] = "";
require('php-includes/connect.php');
session_start();
if (isset($_POST['login_user'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$Hpassword = hash('sha512', $_POST['password']);
$query = "SELECT * FROM user WHERE email='$email' AND password='$Hpassword'";
$mysqli_query = mysqli_query($con, $query);
$_SESSION['userid'] = $email;
$_SESSION['id'] = session_id();
$_SESSION['login_type'] = "user";
$_SESSION['user_id'] = $row['user_id'];
echo '<script>alert("Login Success.");window.location.assign("home.php");</script>';
}
}
please help me
You are not checked here if username and password are correct or not.
if (count($errors) == 0) {
$Hpassword = hash('sha512', $_POST['password']);
$query = "SELECT * FROM user WHERE email='$email' AND password='$Hpassword'";
$mysqli_query = mysqli_query($con, $query);
$_SESSION['userid'] = $email;
$_SESSION['id'] = session_id();
$_SESSION['login_type'] = "user";
$_SESSION['user_id'] = $row['user_id'];
echo '<script>alert("Login Success.");window.location.assign("home.php");</script>';
}
Please correct it using if condition is there any field match with that username or password as below
if(count($mysqli_query)>0)
{
echo '<script>alert("Login Success.");window.location.assign("home.php");</script>';
}
You are getting login successful because there is no script which can track that provided password is in-correct or correct. So you need to add following if-statement for checking it,
if(mysqli_num_rows($mysqli_query) > 0){
$_SESSION['userid'] = $email;
$_SESSION['id'] = session_id();
$_SESSION['login_type'] = "user";
$_SESSION['user_id'] = $row['user_id'];
echo '<script>alert("Login Success.");window.location.assign("home.php");</script>';
}
mysqli_num_rows() will get the rows of match data from database and if there is row the if-statement will be true and then you will only get successful login. Other wise it will be fail and you can show error to user.

what could be wrong with my code, its telling wrong information added yet its correct information. thanks php

This is my code
<?php
$con = mysqli_connect("localhost","root","","system_database");
if(isset($_POST['Submit'])){
$Username = trim($_POST['Username']);
$password = trim($_POST['password']);
// encrypt password before submiting it
$password_encrypted = crypt($password, 'is'); // "is" is the salt
$sql = "SELECT * FROM register WHERE Username = '$Username' AND password='$password_encrypted'";
$query = $con -> query($sql);
$result = mysqli_num_rows($query);
if($result == true){
header ("location: report.php");
} else {
echo "username or password wrong";
}
}
?>
add like this
<?php
$con = mysqli_connect("localhost","root","","system_database");
if(isset($_POST['Submit'])){
$Username = trim($_POST['Username']);
$password = trim($_POST['password']);
if(!empty($Username) && !empty($password)){
$Username = mysqli_real_escape_string($con,$Username);
$password = mysqli_real_escape_string($con,$password);
// encrypt password before submiting it
$password_encrypted = crypt($password, 'is'); // "is" is the salt
$sql = "SELECT * FROM register WHERE Username = '{$Username}' AND password='{$password_encrypted}'";
if($result = mysqli_query($con,$sql)){
if(mysqli_num_rows($result) > 0){
mysqli_free_result($result);
header("Location: report.php");
}else{
echo "username or password wrong";
}
}
}else{
echo "username or password not found";
}
}
?>

Multiple User Type Login Through Single Login Page Issue

I am working on php and mysql code on making access to different pages based on the role of the user, through one Login Page.
Its working good for 'admin' page ..
but not able to login with 'normal type'
Little Help is really appreciated, Thank You
Here is my Code
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query) ;
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result) ;
if ($count == 1) {
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
}
elseif($row['user_type'] = 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
}
?>
Move your session code after if condition and then redirect. Also is there any specific reason to store password in session. == missing
Use proper filters for inputs.
if ($count == 1) {
if(!empty($row['user_type'])) {
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
//$_SESSION['password'] = $row['user_pass'];
}
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
}
elseif($row['user_type'] == 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
The logic test for the normal user was using a single = sign which sets a value rather than tests for equality - it needs to be ==
Also, I think the WRONG USERNAME OR PASSWORD wa at the wrong level - it needs to be the else to the record count
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result);
if ($count == 1) {
if($row['user_type'] == 'admin') {
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
/* require `==` here */
} elseif( $row['user_type'] == 'normal' ) {
header('Location: index.php');
} else {
die('unknown/unhandled user level');
}
/* changed location of this by one level */
} else {
echo "WRONG USERNAME OR PASSWORD";
}
}
?>
This is function for login.
It presumes password come from user with sha512 encryption (see js libs like https://github.com/emn178/js-sha512) - it's good for non-encrypted connections.
It uses salt, and have some protection from brute force, CSRF, XSS and SQL-injection.
static public function db_login($email, $p)
{
if ($stmt = Site::$db->prepare(
"SELECT id, password, salt, name
FROM user
JOIN contact ON contact_id = id
WHERE email = ?
LIMIT 1")
) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $db_password, $salt, $name);
$stmt->fetch();
// hash the password with the unique salt
$p = hash('sha512', $p . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (self::checkBrute($user_id) == true) {
// Account is locked
$res['code'] = 0;
$res['reason'] = 'trylimit';
$res['message'] = 'You try too many times. Come back on 30 minutes';
return $res;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $p) {
// Password is correct!
// Get the user-agent string of the user.
// CSRF
$user_browser = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_SPECIAL_CHARS);
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
Login::sec_session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = htmlspecialchars($email);
$_SESSION['name'] = htmlspecialchars($name);
$_SESSION['token'] = md5(uniqid(rand(), TRUE));
$_SESSION['login_string'] = hash('sha512', $p . $user_browser);
session_write_close();
// Login successful
$res['isLogined'] = 1;
$res['code'] = 1;
$res['name'] = $name;
$res['id'] = $user_id;
return $res;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
Site::$db->query("INSERT INTO login_attempts(user_id, time) VALUES ('$user_id', '$now')");
$res['code'] = 0;
$res['reason'] = 'pass';
$res['message'] = 'Wrong password';
return $res;
}
}
} else {
// No user exists.
$res['code'] = 0;
$res['reason'] = 'user';
$res['message'] = 'We have no such email';
return $res;
}
}
$res['code'] = 0;
$res['reason'] = 'SQL-error';
return $res;
}

MySql Password_verify() not working?

during registration, the user's password is saved in the database as an encrypted BCRYPT password.
My question is: Why can't I verify the encrypted database password with the entered password?
CODE:
<?php //POST VARIABLES
$submit = $_POST['login_submit'];
$username = $_POST['login_username'];
$password = $_POST['login_password'];
$email = $_POST['login_email'];
require 'password_config.php';
if(isset($submit)){
require 'db/connect.php';
//PASSWORD VERIFYING
$pass_query = "SELECT password FROM users WHERE email='$email'";
$queried = mysql_query($pass_query);
while($row = mysql_fetch_array($queried)){
$user_pass = $row['password'];
$veri_password = password_verify($password, $user_pass);
}
//CHECKING NUM ROWS
$sql = "SELECT id, username FROM users WHERE password='$veri_password' AND email='$email'";
$entered_user = mysql_query($sql);
$num_rows = mysql_num_rows($entered_user);
//ERRS ARRAY DECLARED
$errors = array();
//FURTHER VERIFYING
if( $num_rows != 1 )
{
$errors[] = '-Account does not exist ';
}
elseif( $num_rows == 1 )
{
session_start();
while($row = mysql_fetch_array($entered_user)){
$_SESSION['key'] === true;
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $email;
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $password;
header('Location: profile.php');
exit();
}
}
}
?>
I'm receiving an error that says 'account does not exist' even when I enter valid information.
Thanks,
-Eugene
EDIT CHANGED TO THIS:
<?php //POST VARIABLES
$submit = $_POST['login_submit'];
$username = $_POST['login_username'];
$password = $_POST['login_password'];
$email = $_POST['login_email'];
require 'password_config.php';
if(isset($submit)){
require 'db/connect.php';
//PASSWORD VERIFYING
$pass_query = "SELECT password FROM users WHERE email='$email'";
$queried = mysql_query($pass_query);
while($row = mysql_fetch_array($queried)){
$user_pass = $row['password'];
$veri_password = password_verify($password, $user_pass);
}
if($veri_password === true){
//CHECKING NUM ROWS
$sql = "SELECT id, username FROM users WHERE password='$user_pass' AND email='$email'";
$entered_user = mysql_query($sql);
$num_rows = mysql_num_rows($entered_user);
//ERRS ARRAY ESTABLISHED
$errors = array();
//FURTHER VERIFYING
if( $num_rows != 1 )
{
$errors[] = '-Account does not exist ';
}
elseif( $num_rows == 1 )
{
session_start();
while($row = mysql_fetch_array($entered_user)){
$_SESSION['key'] === true;
$_SESSION['id'] = $row['id'];
$_SESSION['email'] = $email;
$_SESSION['user'] = $row['username'];
$_SESSION['pass'] = $password;
header('Location: profile.php');
exit();
}
}
}
}
?>
change to:
$sql = "SELECT id, username FROM users WHERE email='$email'";
Also change:
$veri_password = password_verify($password, $user_pass);
to
if(!password_verify($password, $user_pass)){
echo 'invalid password';
exit;
}
anyway, your code is vulnerable to sql injection. please consider using prepared statements in your queries or escape input strings with mysql_real_escape_string. . And also it is recommended to use mysqli or pdo instead of procedural methods

Login PHP doesn't select right user

So, my problem is that I can't log in as any other user with my login script in PHP, it only selects the last row in the table.
<?php
require_once('core/config.php');
if(isset($_POST['lSubmit'])) {
$result = $mysqli->query("SELECT * FROM cms_users");
while($row = $result->fetch_object() ) {
$username = $row->username;
$password = $row->password;
$id = $row->id;
$Rank = $row->Rank;
$fail = "";
}
if($_POST['username'] == $username && hash("SHA512", "SHA512", $_POST['password'] + "QxLUF1bgIAdeQX") == $password) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: index.php?ID=$id&Username=$username");
} else
header("Location: login.php?fail=true");
$fail = "Username and/or password is wrong!";
}
} else {
header("Location: login.php");
$fail = "Username and/or password is wrong!";
}
Your query select several rows :
$mysqli->query("SELECT * FROM cms_users");
You need to select the user in the table with the username and password passed. If a record will be fetch, that one is the user, otherwise it's a wrong login..
Myabe you can try it like this:
<?php
require_once('core/config.php');
if(isset($_POST['lSubmit'])) {
$result = $mysqli->query("SELECT * FROM cms_users where username='".$_POST['username']."'");
while($row = $result->fetch_object() ) {
$username = $row->username;
$password = $row->password;
$id = $row->id;
$Rank = $row->Rank;
$fail = "";
}
if(hash("SHA512", "SHA512", $_POST['password'] . "QxLUF1bgIAdeQX") == $password) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: index.php?ID=$id&Username=$username");
} else
header("Location: login.php?fail=true");
$fail = "Username and/or password is wrong!";
}
} else {
header("Location: login.php");
$fail = "Username and/or password is wrong!";
}
You should not select all users in your user table. Just the one match username is enough

Categories