Can't verify hashed password - php

I have this php login function that doesn't seem to work with a hashed password in my database.
Where var_dump is, it return both values of the hashed password and the member id.
If I move the var_dump after the second if, it will not return anything. Any suggestions?
public function logIn($id, $password)
{
$stmt = $this->link->prepare("SELECT member_id, member_first_name, member_password FROM members WHERE member_id = ? ");
$stmt->bind_param('i', $id);
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$dbMember_id = $row['member_id'];
$dbMember_first_name = $row['member_first_name'];
$dbpassword = $row['member_password'];
}
if($id == $dbMember_id)
{
var_dump($dbpassword);
var_dump($dbMember_id);
if(password_verify($password,$dbpassword))
{
session_start();
$_SESSION['session_member_first_name'] = $dbMember_first_name;
$_SESSION['session_member_id'] = $dbMember_id;
$_SESSION['last_acted_on'] = time();
}
}
}
}
Thanks

Related

Unable to get result using array_shift()

When i try to verify user data by verify_user method
<?php
public static function verify_user ($username , $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$query = "SELECT * FROM users WHERE username = '{$username}' and password = '{$password}' LIMIT 1";
$result_array = self::find_this_query($query);
if (!empty($result_array)) {
$result_array = array_shift($result_array);
return $result_array;
} else {
return false;
}
}
here also my find_this_query method
public static function find_this_query ($enter_here_your_sql_query)
{
global $database;
$result = $database->query($enter_here_your_sql_query);
return $result;
}
and try to login a user here also my login.php code
<?php
if($session->is_signed_in()) {
redirect("index.php");
}
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
//method to check db user
$user_found = User::verify_user($username , $password);
if ($user_found) {
$session->login($user_found);
redirect("index.php");
} else {
$the_message = "<p class='alert alert-warning' style='color: grey'>Your password or username is incorrect</p>";
$username = "";
$password = "";
}
?>
i get that error on login page
Warning: array_shift() expects parameter 1 to be array, object given in /admin/includes/User.php on line 189
here line 189 from user.php class
$result_array = array_shift($result_array);
What i do wrong here?
$database->query() does not return an array, it returns an object. Try using $database->fetch_array().
The mysqli::query() function doesn't return an array, it returns a mysqli_result object.
mysqli_result implements the Traversable interface, which allows you to use some array operations on it like foreach, but most other array operations don't work. In particular, you can't use array_shift() on this object.
Instead of
$result_array = array_shift($result_array);
return $result_array;
use:
$row = $result_array->fetch_assoc();
return $row;
i solve that issue by the Help give me Barmar.
Here my updated verify_user function
public static function verify_user ($username , $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$query = "SELECT * FROM users WHERE username = '{$username}' and password = '{$password}' LIMIT 1";
$result_array = self::find_this_query($query);
if (!empty($result_array)) {
$result_array = $result_array->fetch_array();
return $result_array;
}else{
return false;
}
}
and here my updated login.php
if($session->is_signed_in()) {
redirect("index.php");
}
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
//method to check db user
$user_found = User::verify_user($username , $password);
$user = User::instantiation($user_found);
$user_id = $user->id;
if ($user_id){
$session->login($user);
redirect("index.php");
} else {
$the_message = "<p class='alert alert-warning' style='color: grey'>Your password or username is incorrect</p>";
$username = "";
$password = "";
}

returning values from within functions

I have defined a function to check user credentials and would like it to return true if the auth passed and false if it failed. my function is defined as follows:
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
return $logged_in;
}
the problem I am running into is this, when I call the function and try to use what should be the returned value I get an error that the variable is not defined.
_userLogin($username, $password);
if ($logged_in == True){
'do something';
} else {
'do something else'
}
what am I doing wrong?
You are trying to use the variable $logged_in that is defined in function _userLogin outside the block. Assign the return value that is returned by the function like,
$logged_in = _userLogin($username, $password)
if ($logged_in == True){
'do something';
} else {
'do something else'
}
Also you will always receive TRUE because you are accessing variables $salt, $password outside the if block where they are being retrieved thus the fields not being assigned properly.
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in = false;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
$dbpass = '';
$salt = '';
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
}
}
return $logged_in;
}
PLEASE NOTE: I did not perform any logic checks other than fix your syntax
Replace your branching (where you use the function) with the simpler:
if( _userLogin($username, $password) ){
//success
}else{
//failure
}

Prepared statement for login function PHP

I am trying to write a parametrised login function in PHP.
The function should get the $id and $pass bind and execute statement and return an associative array from the database with $id, $password, $user_first_name.
Checking for user id and password validation, if true the session should start and set the session with the username from the database.
For some reason I can't get this working. Any suggestions?
Thanks!
public function logIn($id, $password)
{
$stmt = $this->link->prepare("SELECT user_id, user_name, user_password FROM Users WHERE user_id = ? ");
$stms->bind_param('i', $user_id);
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$dbuser_id = $row['user_id'];
$dbpassword = $row['user_password'];
$dbuser_first_name = $row['user_first_name'];
}
if($id == $dbuser_id and $password == $dbpassword)
{
session_start();
$_SESSION['session_user_first_name'] = $dbuser_first_name;
}
else
{
session_unset();
echo "Credentials do not match";
}
}
}
You have
$stms->bind_param('i', $user_id);
But your function signature is:
public function logIn($id, $password)
So you probably want:
$stms->bind_param('i', $id);
Have a look at $stms->bind_param('i', $user_id);:
stms should be stmt
$user_id should be $id
...

Fatal error: Call to undefined method User->get_fullname()

I have problem with get data from database.
This is my function:
public function get_fullname($uid)
{
$result = mysql_query("SELECT name FROM users WHERE uid = $uid");
var_dump(mysql_result($result));
if(mysql_result($result)>0){
//$user_data = mysql_fetch_array($result);
echo $user_data['name'];
}
else{
print_r('chuj');
}
}
and this is my function call:
$uid = $_SESSION['uid'];
$user = new User();
$register = $user->get_fullname($uid);
What is wrong with my code?
Full class in file Functions.php:
include_once 'config.php';
class User
{
//Połączenie z bazą danych
public function __construct()
{
$db = new DB_Class();
}
//Rejestracja
public function register_user($name, $username, $password, $email)
{
$password = md5($password);
$sql = mysql_query("SELECT uid from users WHERE username = '$username' or email = '$email'");
$no_rows = mysql_num_rows($sql);
if ($no_rows == 0)
{
$result = mysql_query("INSERT INTO users(username, password, name, email) values ('$username', '$password','$name','$email')") or die(mysql_error());
return $result;
}
else
{
return FALSE;
}
}
//Logowanie
public function check_login($emailusername, $password)
{
$password = md5($password);
$result = mysql_query("SELECT uid from users WHERE email = '$emailusername' or username='$emailusername' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
var_dump($_SESSION);
return TRUE;
}
else
{
return FALSE;
}
}
//Pobieranie imienia
public function get_fullname($uid)
{
$result = mysql_query("SELECT * FROM users WHERE uid ='".$uid."'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if($no_rows>0){
$user_data = mysql_fetch_array($result);
//echo $user_data['name'];
return $user_data['name'];
}
else{
print_r('chuj');
return FALSE;
}
}
//Sesja
public function get_session()
{
return $_SESSION['login'];
}
//Wylogowanie
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}
}
?>
Fatal error: Call to undefined method User->get_fullname()
Rizier123's comment is correct, but not the cause of your problem.
I tried to reproduce the error but failed. That means that probably you're using an old version somewhere. If you're using FTP or the like, are you sure you uploaded the User class since you added the function?
Also, make sure that the most recent User class is included in the file where you're using it.

PHP PDO Logging Into Account

<?php
function login($database, $username, $password) {
$query = "SELECT * FROM `users` WHERE username=':username'";
$query = $database->prepare($query);
$query->execute(array(':username' => $username));
$rowcount = $query->rowCount();
if($rowcount == 1){
$row = mysql_fetch_array($query);
$dbPass = $row["password"];
if($password == $dbPass){
session_start();
$dbId = $row["id"];
$dbUser = $row["username"];
$dbEmail = $row["email"];
$dbFirstname = $row["firstname"];
$dbLastname = $row["lastname"];
//Register Session Variables
$_SESSION['id'] = $dbId;
$_SESSION['username'] = $dbUser;
$_SESSION['email'] = $dbEmail;
$_SESSION['name'] = $dbFirstname." ".$dbLastname;
return true;
} else
return false;
} else
return false;
}
?>
This is a PHP code snippet from a project I am globally converting to PDO. This is the functions.php file for the login page. Obviously it is not fully converted to PDO so don't criticize that, but basically in the login.php file I have it access this method, and pass the database(which is required in), the username, and the password from the form. I setup a basic query to find all users with the username input of the form. Then i prepare, and execute the query. I then need a row count, so I setup a $rowcount variable running the rowCount() method on the query, but the code does not move past there. The rowcount is == 0 when I echo it out so it won't proceed to the following if statement. Am I doing something wrong with the PDO or something? Or the rowCount(). My suspicion is that perhaps I am calling the rowCount() too late, so I tried moving it up before I execute the $query but no luck. Thank you!
___EDIT___
<?php
session_start();
function login($database, $username, $password) {
$query = "SELECT * FROM `users` WHERE username=':username'";
$query = $database->prepare($query);
$query->execute(array(':username' => $username));
if($query->rowCount()){
$row = $query->fetch();
echo $row;
$dbPass = $row["password"];
if($password == $dbPass){
$dbId = $row["id"];
$dbUser = $row["username"];
$dbEmail = $row["email"];
$dbFirstname = $row["firstname"];
$dbLastname = $row["lastname"];
//Register Session Variables
$_SESSION['id'] = $dbId;
$_SESSION['username'] = $dbUser;
$_SESSION['email'] = $dbEmail;
$_SESSION['name'] = $dbFirstname." ".$dbLastname;
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
Don't mix pdo and mysql_ functions together. NEVER!
Don't store password in plain text. NEVER! Instead try Password_compat !
First:
Is to replace
$row = mysql_fetch_array($query);
with
$query->fetchAll(PDO::FETCH_ASSOC)
Second:
session_start() should appear at the top of your script, not inside your function.
Third:
Is to replace
$rowcount = $query->rowCount();
if($rowcount == 1){
//
}
with this:
if($query->rowCount()){}
Fourth:
This is BAD!!
return true;
} else
return false;
} else
return false;
}
Always, use a complete delimiter. You are instilling a bad-codding practice, that will haunt you for life.
Simple do
if($foo){
if(){
//do something
}else if{
//do something
}else{
//do something
}
}
Fifth:
~Not good, but definitely better that your approach.
function small_query(pdo $pdo, $query, array $value){
$stmt = $pdo->prepare($query);
$stmt->execute($value);
return $stmt->fetchAll();
}
$pdo = new PDO('mysql:host=localhost; dbname=foo', 'root', 'pass');
$result = small_query($pdo, "SELECT * FROM users WHERE name = ?", array($_POST['name']))
EDIT.
Since you seem to love your code so much, I have done it your way. Try this:
<?php
session_start();
function login($database, $username, $password){
$query = "SELECT * FROM users WHERE username = ?";
$stmt = $database->prepare($query);
$stmt->execute(array($username));
if($stmt->rowCount()){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_SESSION["id"] = $result["id"];
$_SESSION["username"] = $result["username"];
$_SESSION["email"] = $result["email"];
return true;
}else{
return false;
}
}

Categories