PHP Error in validating SESSION variable - php

So I've made a login system here, it initiates a session, checks if the password is correct and then sets the session variables.
Here are a few things you might want to note:
It successfully logs in
There is no problem with the mysql connection
All files are places correctly in folders
There are no warnings or error messages
The MYSQL Table structure is correct and there are no errors in database
Note: all functions I'm about to define are in the same file 'functions.php'
Over here we have the session function
include_once("global_config.php");
include_once("db_connect.php");
function sec_session_start()
{
$session_name = 'sec_session_id';
$secure = SECURE;
$httponly = true;
if(ini_set('session.use_only_cookies', 1) === FALSE)
{
echo "Could not initiate a secure session";
exit;
}
$cookieparams = session_get_cookie_params();
session_set_cookie_params($cookieparams['lifetime'],$cookieparams['path'],$cookieparams['domain'],$secure,$httponly);
session_name($session_name);
session_start();
session_regenerate_id();
}
The global_config file define the mysql password, database, user and host and the db_connect file simply return the mysqli_connect to connect to the database.
And this over here is the login function
function login($user,$pass){
sec_session_start();
$link=linkit();
if(empty($user) || empty($pass) || !isset($user) || !isset($pass)){
echo "Error Code: 313, Please contact network administrator for more information";
exit;
}else{
$usercheck = "SELECT `id`,`username`,`password`,`salt` FROM `".LOGINTABLE."` WHERE `username`=? LIMIT 1";
if($stmt=$link->prepare($usercheck)){
$stmt->bind_param('s',$user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id,$username,$realpassword,$salt);
$stmt->fetch();
$stmt->close();
if(empty($realpassword)){
echo 'Unrecognized Username, Please enter a valid username';
exit;
}else{
if($realpassword===$pass){
$_SESSION['username'] = $user;
$_SESSION['user_id'] = $id;
$_SESSION['login_string'] = hash('sha512',$pass);
return true;
}else{
echo "Invalid Password!";
exit;
}
}
}
}
}
The linkit() method is the one defined in db_connect.php which returns mysqli_connect. Also note that the script successfully makes it to setting the Session variable which means that it does return true.
NOW THE PROBLEM is this, when I'm checking for logged in status
function check_login()
{
if(isset($_SESSION['user_id']) &&
isset($_SESSION['login_string']) && isset($_SESSION['username']))
{
$user_id = $_SESSION['user_id'];
$username = $_SESSIOOO['username'];
$login_string = $_SESSION['login_string'];
$pwd_check = "SELECT `password` FROM `".LOGINTABLE."` WHERE `user_id`=? LIMIT 1";
if($stmt = linkit()->prepare($pwd_check))
{
$stmt->bind_param('s',$user_id);
$stmt->execute();
$stmt->bind_result($realpassword);
$stmt->fetch();
$stmt->close();
$hashedpass = hash('sha512',$realpassword);
if($login_string==$hashedpass){
return true;
}else{
return false;
}
}else{
return true;
}
}else{
return false;
}
}
AND FINALLY, this is WHERE I process my login script. Also note that there are no errors in POST methods or anything else. They all work fine.
This is in a separate php file and NOT in the functions.php
<?php
include_once '../includes/functions.php';
if(empty($_POST['loginuser']) || !isset($_POST['loginuser']) || !isset($_POST['id']) || empty($_POST['id']) || !isset($_POST['password']) || empty($_POST['password']))
{
echo "Error Code: 412, Please contact network administrator for more information";
exit;
}else{
if($_POST['loginuser']==="true")
{
$user = $_POST['id'];
$pass = $_POST['password'];
if(login($user,$pass)==true)
{
echo "Logged In!";
}else
{
echo "Failed to login, check your username or password";
}
}
}
?>
Additional Information :
The response I get is "Logged In"
Session is successfully creaated
PROBLEM: When I check for the login status, it returns false despite of having the session variables set.

In check_login you are hashing the password and then compare the unhashed password
function check_login()
{
if(isset($_SESSION['user_id']) &&
isset($_SESSION['login_string']) && isset($_SESSION['username']))
{
$user_id = $_SESSION['user_id'];
$username = $_SESSIOOO['username'];
$login_string = $_SESSION['login_string'];
$pwd_check = "SELECT `password` FROM `".LOGINTABLE."` WHERE `user_id`=? LIMIT 1";
if($stmt = linkit()->prepare($pwd_check))
{
$stmt->bind_param('s',$user_id);
$stmt->execute();
$stmt->bind_result($realpassword);
$stmt->fetch();
$stmt->close();
$hashedpass = hash('sha512',$realpassword);
if($login_string==$hashedpass ){
return true;
}else{
return false;
}
}else{
return true;
}
}else{
return false;
}
}

Related

I can't get userid from session?

some help if you wish please for beginner user
will you please show me where is my code problem ?
i want to get user id from $_SESSION['userid']
but it's not working
i success to get username but not the id
i include session_start(); on each page to want to use it
but it's not showing the user id
only username working
here are my code
<?php
include("conn.php");
// variable declaration
$userid = "";
$username = "";
$email = "";
$errors = array();
$_SESSION['success'] = "";
// call the login() function if register_btn is clicked
if (isset($_POST['login_btn'])) {
login();
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
unset($_SESSION['username']);
unset($_SESSION['userid']);
unset($_SESSION['user_type']);
header("location: ../login.php");
}
// return user array from their id
function getUserById($id){
global $conn;
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
// LOGIN USER
function login(){
global $conn, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
// attempt login if no errors on form
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 1) { // user found
// Storing username in session variable
session_start();
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
$userid=$row['id'];
$username=$row['username'];
$user_type=$row['user_type'];
$_SESSION['username'] = $username;
$_SESSION['userid'] = $userid; // <-this variable should now exist
$_SESSION['user_type'] = $user_type;
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: admin/home.php');
}else{
if ($logged_in_user['user_type'] == 'superuser') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: superuser/home.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
} }else {
array_push($errors, "Wrong username/password combination");
}
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
function isSuperuser()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'superuser' ) {
return true;
}else{
return false;
}
}
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
// escape string
function e($val){
global $conn;
return mysqli_real_escape_string($conn, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
?>
As far as i can tell, your script would run.
Though please note that when using with sessions and $_SESSION globals, you have to initialise it first by adding session_start(); at the top of your page.
You should also dig into using PDO rather than mysqli or mysql.
I know this looks complicated, but it's the safest way to handle database queries.
Also don't use md5, use password_hash();
I also recommend adding var_dump($row); in this if statement, to see what data you are working with:
if (mysqli_num_rows($results) == 1) { // user found

storing user_id in session variable

so I have this site where drivers can login and register.
at the moment i can store the username in a session variable, im trying to do the same for the user_id so the user can later retrieve it when adding more details for a job.
heres what I got so far:
function selectUser($conn, $username, $password, $userID)
{
$query = "SELECT * FROM login WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
//$stmt->bindValue(':user_ID', $userID);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_OBJ))
{
if (md5($password) == $row->password) {
$_SESSION['username'] = $username;
$_SESSION['user_ID'] = $userID;
// $_SESSION['password'] = $password;
echo "Welcome, you are now logged in as " . $username;
return true;
}
return false;
}
else
{
//echo "Your details were not found";
return false;
}
}
when the driver accesses another page:
<?php
if(!isset($_SESSION))
{
session_start();
}
require_once ("config.inc.php");
try
{
$conn = new PDO(DB_DATA_SOURCE, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $exception)
{
echo "Oh no, there was a problem" . $exception->getMessage();
}
if(isset($_SESSION["username"]))
{
echo "Welcome, you are now logged in as <b>".$_SESSION['username']."</b> <img class='clientView' src='images/loginIcon.png' alt='client'>"; }
else {
echo "You are currently not logged in";
}
$login = $_SESSION['user_ID'];
$query = "SELECT * FROM login WHERE user_ID = :login";
$term = $conn->prepare($query);
$term->bindValue(':login', $login);
$term->execute();
$login = $term->fetch(PDO::FETCH_OBJ);
print_r($_SESSION);
?>
tested it using print r and for some reason it doesnt seem to be collecting the user_ID.
am i doing something wrong?
upon test: https://snag.gy/6bGd5m.jpg
when calling the function:
$username=trim($_POST['username']);
$password=$_POST['password'];
$username= htmlspecialchars($username);
$validForm = true;
if (empty($_POST["username"]))
{
$validForm=false;
}
if (empty($_POST["password"]))
{
$validForm=false;
}
if (!$validForm) {
$error = "please ensure all fields are filled in";
include("add.php");
return false;
}
$conn=getConn();
$successLogin=selectUser($conn,$username,$password);
if($successLogin)
{
header( 'Location: profile.php');
}else{
$error = "The details you have entered are incorrect";
include("add.php");
}
Debug.
Where do you store the value in the session state?:
$_SESSION['user_ID'] = $userID;
Ok, so where does $userID come from?:
function selectUser($conn, $username, $password, $userID)
{
//...
Ok, so where does the function parameter come from?:
selectUser($conn,$username,$password)
Nowhere. You never supplied a value to be stored in session, so no value was stored in session.
It seems unlikely that you actually want to supply the User ID to the function. Instead, you probably want to supply just the username and password as you currently do and then get the User ID from the database. Which might look more like this:
$_SESSION['user_ID'] = $row["user_ID"];
Or perhaps:
$_SESSION['user_ID'] = $row->user_id;
Or however you get values from your $row object.
But basically the important lesson here is... When a value isn't what you expect it to be, trace back where that value came from. Chances are you have a false assumption somewhere.

Php user session not being set

Boy am I confused. So I had a working login system when I was working a different database name. I changed over all the names and files to fit the new sql database. Everything seems to work except that my login check says that I am not logged in. It seems to be a problem that the session is not set.
I first have a login page that sends you through this page successfully (I end up at member_home):
<?php
include_once './../functions.php';
include_once './../dbConnect.php';
sec_session_start(); // custom way of starting a PHP session.
if (isset($_POST['user'], $_POST['p'])) {
$user = $_POST['user'];
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
echo 'hashed password length wrong';
}
//$password = $_POST['p']; // The hashed password.
if (login($user, $password, $dbConnection) == true) {
// Login success
$con = #require './../dbConnect.php';
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
$result = mysqli_query($dbConnection,"SELECT * FROM members WHERE user = '". $_SESSION['user'] ."'");
$row = mysqli_fetch_array($result);
$passkey1 = $row['confirmcode'];
header('Location: http://www.examplewebsite.com/member_home.php?passkey='.$passkey1);
}
}
else {
// Login failed
header('Location: ../login_page.php?error=1');
echo 'login failed';
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
?>
On my member home page it requires that the user is logged in via this function login_check:
function login_check($dbConnection) {
// Check if all session variables are set
//this session is not being set....
if (isset($_SESSION['user_id'],
$_SESSION['user'],
$_SESSION['login_string'])) {
header('Location: http://www.examplewebsite.com/index.php');
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['user'];
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if ($stmt = $dbConnection->prepare("SELECT password
FROM members
WHERE id = ? LIMIT 1")) {
// Bind "$user_id" to parameter.
$stmt->bind_param('i', $user_id);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if ($stmt->num_rows == 1) {
//we are not making it to this if statement
// If the user exists get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
$login_check = hash('sha512', $password . $user_browser);
if ($login_check == $login_string) {
// Logged In!!!!
return true;
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
}
I know I don't pass the first if statement because I was not relocated via the header check.
Here is the sec_session_start() function and I've tested and seen that it does indeed go through this entire function:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
}
So for some reason, my loginCheck function always fails and I can't figure out why the session is not set! Is something wrong here or would it be elsewhere? Can someone lead me in a direction to check for other errors?
The problem only started occurring after switching all the databasenames and related, but I can't find anywhere where the text is different.
Here is my login variable, responsible for binding everything:
function login($user, $password, $dbConnection) {
global $errors;
$errors = 1;
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $dbConnection->prepare("SELECT ID, user, paid, password, salt
FROM members WHERE user = ? LIMIT 1")) {
$stmt->bind_param('s', $user); // Bind "$user" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $user, $paid, $db_password, $salt);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
$errors= 2;
if ($stmt->num_rows > 0) {
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$user = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$user);
$_SESSION['user'] = $user;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
// Login successful.
$errors=3;
return true;
} else {
return false;
}
}
else {
// No user exists.
return false;
}
}
}
I actually CAN'T get the $errors variable to post in member_home neither.
I mean again, the problem seems to be that after I send the user to member_home, there is no longer a defined $_SESSION['user']. It just seems to all disappear after the header(location:member_home)

Where is the logical flaw in this PHP login code?

There is definitely a logical flaw somewhere in this code, but I can't find it. The issue is that regardless of input, it echo's success (simulating a redirect to the main page). I don't know why. Here's the code:
$signIn = new UserService($dbuser, $dbpass, $dbhost, $dbname); //Create new class instance
$signIn->sec_session_start(); //Begin session
$_SESSION['token'] = $token; //Store token valualbe in super global variable
//***************************************************************************************//
//***************************************************************************************//
//Begin Login Functions
if(isset($_POST['username'], $_POST['password'],$_POST['siteToken'])) {
//Assign POST submissions to passable php variables
$username = $_POST['username'];
$password = $_POST['password'];
$passedToken = $_POST['siteToken'];
//Check Token Values (prevent CSRF attacks)
/*
if($passedToken != $_SESSION['token']) {
$error = "CSRF attack detected. Please close your browser and try again.";
$signIn->csrfAttackLog($username);
echo $error;
exit();
}
*/
//Test if both fields are not null
if($username == "" || $password = "")
{
$error = "Not all fields were entered<br />";
echo $error;
exit();
}
//Start login process
else
{
$success = $signIn->login($username, $password);
if ($success == true)
{ //Login Successful
echo "Success!"; //Direct to main page.
exit();
}
//Specific login failure determination
else
{
switch ($success){
case 1:
$error = "Your account has been locked.";
echo $error;
break;
case 2:
$error = "Invalid Username/Password (2)";
echo $error;
break;
case 3:
$error = "Invalid Username/Password";
echo $error;
break;
case 4:
$error = "Invalid Username/Password (3)";
echo $error;
break;
}
}
}
Here's the login class method:
public function login($username, $password)
{
//****************//
$this->username = $username;
$this->password = $password;
$user_Id = "";
$user = "";
$hashPassword = "";
$dbPassword = "";
$salt = "";
$userBrowser = "";
//**************// Local declerations
$this->connect(); //connect to database
if ($stmt = $this->dbh->prepare("SELECT UserId, Username, Pass, Salt FROM user WHERE Username = :param1 LIMIT 1")) //Prepared procedure
{
$stmt->bindParam(':param1', $this->username); //Bind $this->username to parameter
$stmt->execute(); //Execute the prepared query
if ($stmt->rowCount() == 1) //If the user exists
{
$this->user = $stmt->fetch(PDO::FETCH_ASSOC); //Grab the variables from the selected database row
$user_Id = $this->user['UserId']; //Transfer variables from array to local variables
$user = $this->user['Username'];
$dbPassword = $this->user['Pass'];
$salt = $this->user['Salt'];
if($user_Id = "")
echo "Why";
//Check if account has been locked
if($this->checkBrute($user_Id, $this->dbh) == true)
{
//Account is locked
return 1; //Used in userControl as a switch condition: Indicates a locked account
//Possibly send an email here
} else {
$hashPassword = hash('sha512', $this->password.$salt); //Hash the password with the unique salt
if($dbPassword == $hashPassword)
{ //Check if the password in the database matches the password the user submitted
//Password is correct!
$userBrowser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user
$_SESSION['p_id'] = $user_Id; //Store user id to global session variable
$_SESSION['userName'] = $user; //Store username to global session variable
$_SESSION['loginString'] = hash('sha512', $hashPassword.$userBrowser); //Hash the concentanation of the hashedpassword (password + salt) and userBrowser
//Login succesful!!!!!!
return true;
} else {
//Password is not correct
//Record this attempt in the database
$now = time();
$userIp = $_SERVER['REMOTE_ADDR'];
$insert = $this->dbh->query("INSERT INTO loginattempts (UserId, UserIp, EventTime) VALUES ('$user_Id', 'userIP', '$now')");
if($insert == false){
return 2; //Used in userControl as a switch condition: Indicated a failure to log failed login attempt
} else {
return 3; //Used in userControl as a switch condition: Indicates an inccorect password
}
}
}
}
else
{
//No user exists
return 4;
}
}
}
I know the SQL queries work: I've tested them outside this code. I don't understand why it keeps returning true. PHP hasn't thrown any exceptions or errors (and yes, I've read many times "don't write your own login functions. Use one that already works." This is not a public site. I'm just doing it for the heck of it). Any help is appreciated.
Your login code has various return codes - true if everything works, or numbers to indicate various error states. You're then checking the return value with:
if ($success == true)
PHP isn't strongly typed, so it will cast return values to a boolean for that comparison; and any non-0 integer will evaluate to true. To do a type check, as well as a value check, you need to use the strict comparison operator:
if ($success === true)
That will evaluate true if $success is both true and a boolean.

Get user's ID from mysql UPON login and echo to screen php/mysql

login/index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
<?php
if($_SESSION['valid'] == 1){ #user has logged in by creating a session var
echo "<a href='logout.php'>Logout</a>";
}
else{
return false;
}
?>
Once login/index.php is filled out, it validates a valid login with check_buyer.php:
<?php
session_start(); #recall session from index.php where user logged
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt, uUserType FROM User WHERE uUName = '$LoginUserName';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
echo "Invalid Username and/or Password";
return true;
}
function validateUser() {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = (isset($ifUserExists['uID'])) ? $ifUserExists['uID'] : null;
$_SESSION['uUserType'] = 1; // 1 for buyer - 2 for merchant
}
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
else {
validateUser();
}
// If User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
If a valid user is provided, it redirects to buyer/index.php which includes the buyer_profile.php page (farther below):
<?php
session_start();
if($_SESSION['uUserType'] != 1) // error
{
die("
<div class='container_infinity'>
<div class='container_full' style='position:static;'>
<img src='img/error/noAccess.png' style='float:left;' /> <br />
<h2>403 Error: You may not view this page. Access denied.</h2>
</div>
</div>
");
}
function isLoggedIn()
{
return ($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: ../index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
echo 'buyerid: '.$_SESSION['uID'];
require_once('buyer_profile.php');
}
else{
echo "<a href='../index.php'>Login</a>";
}
?>
buyer_profile.php
Which is basic HTML with the session_start(); at the first line
The problem lies in login/buyer/index.php, where echo 'buyerid: '.$_SESSION['uID']; does not display anything. It should be outputting the uID of the user logged in from the SELECT query in the login/check_buyer.php why isn't it storing this value upon logging in??
Anyone??
Perhaps the SELECT query is returning false so $ifUserExists is not having any value set to it (other than false).
You can test this by using print_r($ifUserExists);, which will print out the array if it is a set and valid array; otherwise, it will not print anything.
You can also try this code, that I think might solve the problem.
list($ifUserExists) = ($result) ? #array_values(mysqli_fetch_assoc($result)) : NULL;
$_SESSION["uID"] = ($ifUserExists && $ifUserExists["uId"]) ? $ifUserExists["uId"] : NULL;
# insert your couple other lines of code here, I will not write them to save space
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
elseif ($_SESSION["uID"]) {
validateUser();
}
else {die("error!");}

Categories