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

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!");}

Related

Trying to get login error messages/validation to work on login form?

I have a login system for a member/admin site. The login is working perfectly, but I want to verify the user and give error messages if it's not the correct user or password. So far, with what I have, it will not give any error messages although I'm not getting any errors either.
function error_message(){ $error = '';
$loginName = isset($_REQUEST['loginName']) ? $_REQUEST['loginName'] : "";
$password = isset($_REQUEST['password']) ? $_REQUEST['password'] : "";
{$results = connect($loginName);
$loginName === $results['email'];
$passwords = password_verify($password,$results['password']);
if(!$results) {$error = 'Username not found'; echo $error; header ('Location: home.php');} //if no records returned, set error to no username
else //if found {if ((isset($password)) !== (isset($passwords))) //check password, if matched log him in
{ $error = 'Password is wrong'; echo $error; header('Location: home.php');} //if not matched then set error message
}
}
if(isset($error)) {echo $error; }//if there is an error print it, this can be anywhere in the page
}
This is my connection and how it is logging in:
function connect($loginName) {
global $db;
$query = "SELECT email, level, password FROM members WHERE email ='$loginName'";
$result = $db->query($query);
$results = $result->fetch(PDO::FETCH_ASSOC);
return $results;
}
Login:
function login($loginName, $password) {
$results = connect($loginName);
if(!$results) {
header('Location: /tire/admin/home.php?err=1');
}
if ($loginName === $results['email'] && password_verify($password,$results['password'])) {
$_SESSION['loginName'] = $loginName;
if ($results['level'] === 'a') { // 1 == Administrator
$_SESSION['level'] = 'Administrator';
header('Location: /tire/admin/home.php');
} elseif ($results['level'] === 'm') { // 1 == Member
$_SESSION['level'] = 'Member';
header('Location: /tire/member/home.php');
exit;
}
}
header('Location: /tire/admin/home.php');
}
Wow, that's some nasty code we have here. Let's get started:
Let's first take a look in the connect function:
Gets the row where the email matches the loginName provided.
Return the array with the desired row.
That's correct.
Now let's take a look to the login function:
Retrieves the row where the email matches loginName.
If there is no row (email does not match any user), redirects to home.php of ¿ADMIN? with the variable $err = 1.
Recheck the email (what for?) and verify the password.
If password is correct, it checks permissions and redirects to the correspondent home.php.
Notice that if there is no matches for a permission, it redirects you to admin home.php.
Notice that if the password is incorrect, you do nothing.
I will improve this code:
function login($loginName, $password) {
$results = connect($loginName);
if(!$results) {
header('Location: /tire/error.php?code=1');
}
if (password_verify($password,$results['password'])) {
$_SESSION['loginName'] = $loginName;
if ($results['level'] === 'a') { // 1 == Administrator
$_SESSION['level'] = 'Administrator';
header('Location: /tire/admin/home.php');
} elseif ($results['level'] === 'm') { // 1 == Member
$_SESSION['level'] = 'Member';
header('Location: /tire/member/home.php');
exit;
}
} else {
header('Location: /tire/error.php?code=2');
}
}
And then in error.php (or whatever place you would like to show the errors, it's just an example):
switch($_GET['code']){
case 1:
$error = "Email invalid";
break;
case 2:
$error = "Password invalid";
break;
}
print $error
That being said, I will strongly recommend you to read about exceptions and implement the logic based on that. It's far more clean than the code above, but I didn't want to change your code so drastically.
See: http://php.net/manual/en/language.exceptions.php

PHP Error in validating SESSION variable

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;
}
}

Log in returns blank for incorrect password?

I have been using a tutorial for a registration and log in page. Everything is perfect except when a user inputs an incorrect password.
If no password is entered then the stated error is displayed fine.
If the correct password is entered it logs them in.
If the incorrect password is entered it goes to a blank page?!
I want an incorrect password to display a message just like when the wrong username is entered. I've included my entire login.php code:
include('db.php');
if(!isset($_POST['login'])) {
include('form.php');
} else {
if(isset($_POST['user'])&&$_POST['user']==""||!isset($_POST['user'])) {
$error[] = "Username Field can't be left blank";
$usererror = "1";
}
if(!isset($usererror)) {
$user = mysql_real_escape_string($_POST['user']);
$sql = "SELECT * FROM users WHERE user = '$user'";
if(mysql_num_rows(mysql_query($sql))=="0") {
$error[] = "Can't find a user with this username";
}
}
if(isset($_POST['pass'])&&$_POST['pass']==""||!isset($_POST['pass'])) {
$error[] = "password Field can't be left blank";
}
if(isset($error)) {
if(is_array($error)) {
echo "<div class=\"error\"><span>please check the errors and refill the form<span><br/>";
foreach ($error as $ers) {
echo "<span>".$ers."</span><br/>";
}
echo "</div>";
include('form.php');
}
}
if(!isset($error)) {
$suser=mysql_real_escape_string($_POST['user']);
$spass=md5($_POST['pass']);//for secure passwords
$find = "SELECT * FROM users WHERE user = '$suser' AND password = '$spass'";
if(mysql_num_rows(mysql_query($find))=="1"or die(mysql_error())) {
session_start();
$_SESSION['username'] = $suser;
header("Location: loggedin.php");
} else {
echo "<div class=\"warning\"><span>Some Error occured durring processing your data</div>";
}
}
}
if(mysql_num_rows(mysql_query($find))=="1"or die(mysql_error())){
If wrong password is entered, mysql_num_rows(mysql_query($find)) is 0 so it results in die(mysql_error()). But since there is no mysql_error(), you see a blank page.
Try this
$result = mysql_query($find) or die(mysql_error());
if (mysql_num_rows($result) == 1) {
// proceed
} else {
// authentication failed
}
EDIT: This is just for illustration purpose only. Use MySQLi or PDO when dealing with MySQL.
The code is little bit confusing for me, consider using this code.
<?php
include('db.php');
if(isset($_POST['login'])) {
$username = mysql_real_escape_string($_POST['user']);
$password = md5($_POST['pass']);
if(empty($username) || empty($password)) {
echo "Empty username or password.";
} else {
mysql_query("SELECT * FROM `users` WHERE `user` = '$user' AND `password.md5` = '$password'");
if(mysql_num_rows() == 1) {
// login successfull
session_start();
$_SESSION['username'] = $username;
header("Location: loggedin.php");
} else {
echo "Invalid username or password.";
}
}
} else {
include ('form.php');
}
?>

Get values of userAccount upon Login

I am creating a login system for my website. I want to grab the user's userID (aka a primary key out of the database) to use when they log in.
I have 3 files I'm using:
/index.php - that is basically the login form with a username and password fields. It contains this php code:
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
Once form is submitted, it goes to check_buyer.php (/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;
echo 'sessuID: '.$_SESSION['uID'];
$_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 the credentials are valid, the user is sent to login_new/buyer/index.php
<?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>";
}
?>
The problem is, when I login with valid credentials it sends me to login_new/buyer/index.php with the account, but is not outputting the buyer ID using the code echo 'buyerid: '.$_SESSION['uID']; what am I doing wrong here?
Try commenting the header() redirect and echo the $_SESSION['uID'] right after you set it in function validateUser() to see if the session data is actually set right there

Session Start and Stop Error Php

Index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
include('login_helper.php');
?>
<!--
html form
-->
Login/Logout Links depending on session state:
<?php
if($_SESSION['valid'] == 1){
echo "<a href='logout.php'>Logout</a>";
echo 'userID '.$userid;
}
else{
echo "<a href='index.php'>Login</a>";
}
?>
check_buyer.php
<?php
session_start(); #recall session from index.php where user logged include()
require_once('login_helper.php');
/*
function validateUser()
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] == 1;
$_SESSION['userid'] = $userid;
}
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
*/
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
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);
$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 the user has not logged in
if(!isLoggedIn())
{
echo "<html>
<head>
<meta http-equiv='refresh' content='0'; url=index.php'>
</head>
<body>
</body>
<html>";
die();
}
?>
login_helper.php
<?php
function validateUser()
{
#session_regenerate_id (); //this is a security measure
$_SESSION['valid'] == 1;
$_SESSION['uID'] = $userid;
echo "Session made";
}
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
function logout()
{
session_start();
$_SESSION = array(); //destroy all of the session variables
session_destroy();
echo "
<html>
<head>
<meta http-equiv='refresh' content='0'; url=index.php'>
</head>
<body>
</body>
<html>";
}
?>
pwhome.php
<?php
session_start();
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1){
echo "<a href='logout.php'>Logout</a>";
echo 'userID '.$userid;
}
else{
echo "<a href='index.php'>Login</a>";
}
?>
logout.php
<?php
require_once('login_helper.php');
logout();
?>
Current State: When I visit index.php and login with credentials that are indeed correct, I get a never ending refresh of check_buyer.php
How do I get this to login in properly (from index.php) and redirect me properly to pwhome.php upon providing valid credentials on index.php ?
I wonder with your code, if you want to logout and refresh the index.php with new session value, why dont you put header( 'Location: index.php' ); in your logout function?
So, i think this probably will help, modify your logout.php:
Logout.php
<?php
session_start();
function logout()
{
$_SESSION = array(); //destroy all of the session variables
session_destroy();
echo "logged out?";
header( 'Location: index.php' );
}
logout();
?>
Last Edited :
Try this codes :
Index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
<!--
html form
-->
<?php
if($_SESSION['valid'] == 1){
echo "<a href='logout.php'>Logout</a>";
echo 'userID '.$userid;
}
else{
echo "<a href='index.php'>Login</a>";
}
?>
check_buyer.php
<?php
session_start(); #recall session from index.php where user logged include()
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
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);
$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 the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
function validateUser()
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['uID'] = $userid;
}
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
?>
logout.php
<?php
session_start();
function logout()
{
$_SESSION = array(); //destroy all of the session variables
session_destroy();
header( 'Location: index.php' );
}
logout();
?>
Instead of
header('Location: index.php');
Try meta refresh for page forwarding. After closing the php block, add some HTML code like;
<html>
<head>
<meta http-equiv="refresh" content="0; url=index.php">
</head>
<body>
</body>
<html>
Sometimes session doesn't work as it should when you use header() function for page forwarding.

Categories