Get values of userAccount upon Login - php

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

Related

Can't Tranfer Session ID When trying to allow access to a page when logged in

Hello I am trying to create a login page where the user enters an access code, if correct it will redirect the user to the main index.php, I am trying to only allow access to the index.php page if the user has logged in, but it wont display when logged in.
Phpmyadmin:
Login.php Code
<?php
include("DB.php"); //database connection
session_start();
if(isset($_POST["login"]))
{
if(empty($_POST["code"]))
{
echo '<script>alert("Code Feild is Empty")</script>';
}
else
{
$code = mysqli_real_escape_string($connect, $_POST["code"]);
$query = "SELECT * FROM login";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($code, $row["Code"]))
{
//return true;
header("location:index.php");
}
else
{
//return false;
echo '<script>alert("Wrong User Details")</script>';
}
}
}
else
{
echo '<script>alert("Wrong User Details")</script>';
}
}
}
include("loginpage.html"); //log in forum
?>
Index.php code
<?php
session_start();
if(isset($_SESSION["ID"])){
?>
//website code
<?php
} else{
echo "You Need To Enter the Access Code to enter the site";
}
?>
I fixed it by adding
$_SESSION['auth'] = 1 ;
to login.php when the password gets checked.
then on index.php i added
if(isset($_SESSION["auth"])){
this fixed my problem

.php file security using MAMP

I have generated a php file that has information stored in a database. To access this a person must use a login in page.
However, when you are using MAMP how can you prevent someone from accessing the file through writing the IP address and php file name e.g. 123.456.78.00:80/fileone.php. I want this fileone.php to be hidden and for them to only access it through a login page.
Thanks in advance.
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root","root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if($exists > 0) //IF there are no returning rows or no existing username
{
while($row = mysql_fetch_assoc($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if(($username == $table_users) && ($password == $table_password)) // checks if there are any matching fields
{
if($password == $table_password)
{
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
//echo $table_id;
//echo $page_id;
redirect ($page_id); //take the user to the page specified in the users table
}
else
{
echo "Login Failed";
}
}
else
{
Print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
}
else
{
Print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: ' . $page_id);
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
Login check
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true) {
"Your script"
}
If you have a profile for your users, like a normal user = 0 and an admin = 1 you can do it like this
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true && $_SESSION['profile'] == 1) {
"Your script"
}
Set sessions
To set set the sessions to true you need this
if(isset($_POST['submit'])) {
$_SESSION['loggedIn'] = true;
// for set a profile
$_SESSION['profile'] = 1;
}
Maybe I didn't understand you good, but to be sure I will explain something:
You said attached checklogin.php, but you can't use that to deny access for non members. If they know that the file exists, they can type it in the URL and still read fileone.php. The first coding block need to be in your fileone.php.
Session time
Search in your php.ini for 'session.gc_maxlifetime'. There will be a number and that is the time in seconds.

Checking user login using $_SESSIONS

Below are the following scripts, the first one is checklogin.php. This matches up the username and password that is stored in MYSQL database. Once this information has been checked they will get sent to their personal page by using a redirect function.
The bottom php script is user1's landing page. I want something on there that will confirm that this person has correctly logged in and is not entitled to view this page.
At the moment, when i log in as user1 i get shown the page 3.php, i.e. it's saying that i am not correctly logged in. I know i need to set up a session like:
$_SESSION[logged in'] == 'y';
and i think this should go where the passwords are being compared to what is stored in the database. At the moment I cannot enter my login details and be directed to the correct file at the end. Any help will be much appreciated.
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root", "root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if ($exists > 0) {
//IF there are no returning rows or no existing username
//$_SESSION['logged in'] == 'y';
while ($row = mysql_fetch_assoc($query)) {
//display all rows from query
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if (($username == $table_users) && ($password == $table_password)) {
// checks if there are any matching fields
if ($password == $table_password) {
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
$_SESSION['logged_in'] = 'y';
//echo $table_id;
//echo $page_id;
redirect($page_id); //take the user to the page specified in the users table
} else {
echo "Login Failed";
}
} else {
print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
} else {
print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: '.$page_id);
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
And landing page
<?php
session_start();
//user logged in??
if ($_session['logged in'] != 'Y') {
//No- jump to log in page.
header("location: 3.php");
exit();
}
else
{
echo 'this works';
}
?>
You're defining the session like:
$_SESSION['logged in'] == 'y';
which should be:
$_SESSION['logged in'] = 'y';
yet you check like:
if ($_session['logged in'] != 'Y') {
it should be:
if ($_SESSION['logged in'] != 'y') {
You're checking if it's an uppercase Y while it holds a lowercase y. So it will never succeed.
Also $_SESSION is a superglobal which means:
Superglobals — Superglobals are built-in variables that are always
available in all scopes
and variables are case sensitive.

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

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