Session variable not passing from log in script - php

I am trying to pass a session variable from the log in script to display a Welcome [Username] massage, at the moment its not passing it through - any ideas? I am quite new to PHP so all your comments are greatly appreciated.
The code is as follows.
<?php
ob_start(); // Start output buffering
session_start(); //must call session_start before using any $_SESSION variables
$_SESSION['username'] = $username;
function validateUser()
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
}
$username = isset($_POST['username'])?$_POST['username']:'';
$password = isset($_POST['password'])?$_POST['password']:'';
//connect to the database here
$hostname_PropSuite = "localhost";
$database_PropSuite = "propsuite";
$username_PropSuite = "root";
$password_PropSuite = "root";
$PropSuite = mysql_pconnect($hostname_PropSuite, $username_PropSuite, $password_PropSuite) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_PropSuite, $PropSuite);
$username = mysql_real_escape_string($username);
$query = "SELECT password, salt FROM admin_users WHERE username = '$username';";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result) < 1) //no such user exists
{
header('Location: http://localhost/PropSuite/index.php?login=fail');
die();
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
header('Location: http://localhost/PropSuite/index.php?login=fail');
die();
}
else
{
validateUser(); //sets the session data for this user
}
//redirect to another page or display "login success" message
header('Location: http://localhost/PropSuite/main');
die();
//redirect to another page or display "login success" message
?>

Add username as parameter in the function
function validateUser($username)
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
}
And pass it when you call it
validateUser($username); //sets the session data for this user

I think that your problem is that you are using $_SESSION['username'] = $username; before $username is defined. $username = isset($_POST['username'])?$_POST['username']:''; needs to be above $_SESSION['username'] = $username;.

To access a variable declared in the global scope, from within a function, you have to use global keyword, like so:
function validateUser()
{
global $username;//NEEDED to access $username declared in global scope
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
}

Related

session value lost after redirection in php

PHP session value lost after header redirection in php
Our code
Login.php
<?php
session_start();
include('./includes/variables.php');
include_once('includes/custom-functions.php');
$fn = new custom_functions;
if (isset($_POST['btnLogin'])) {
// get username and password
$username = $db->escapeString($fn->xss_clean($_POST['username']));
$password = $db->escapeString($fn->xss_clean($_POST['password']));
// set time for session timeout
$currentTime = time() + 25200;
$expired = 3600;
// create array variable to handle error
$error = array();
// check whether $username is empty or not
if (empty($username)) {
$error['username'] = "*Username should be filled.";
}
// check whether $password is empty or not
if (empty($password)) {
$error['password'] = "*Password should be filled.";
}
// if username and password is not empty, check in database
if (!empty($username) && !empty($password)) {
// change username to lowercase
$username = strtolower($username);
//encript password to sha256
//$password = md5($password);
// get data from user table
$sql_query = "SELECT * FROM admin WHERE username = '" . $username . "' AND password = '" . $password . "'";
$db->sql($sql_query);
/* store result */
$res = $db->getResult();
// print_r($res);
// die();
$num = $db->numRows($res);
// Close statement object
if ($num == 1) {
$_SESSION['id'] = $res[0]['id'];
$_SESSION['role'] = $res[0]['role'];
$_SESSION['user'] = $username;
$_SESSION['timeout'] = $currentTime + $expired;
//print_r($_SESSION);
//die();
header("location: home.php");
exit();
} else {
$error['failed'] = "<span class='label label-danger'>Invalid Username or Password!</span>";
}
}
}
?>
Home.php
<?php session_start();
print_r($_SESSION);
?>
Output :
array()
We tried the following method
Made sure session_start(); is called before any sessions are
being called
After the header redirect, end the current script using exit();
Made sure cookies are enabled in the browser we were using to test
it on.
Made sure didn't delete or empty the session
Made sure file extension is .php
You have to include you file in which you have initialized session
For example
first file named phpcodeonly.php:
session_start() //put it in start
if(login success){
$_SESSION['email']= $email
}
your other file.php:
include 'phpcodeonly.php'; //on top
<h1> Welcome <?php echo $_SESSION['email']?> </h1>

store $username and $file variables in the $_SESSION after login

From index.php I get the values of the username and password fileds with $_POST
index.php
if(isset($_POST["username"]) && isset($_POST["password"])){
$username = mysql_real_escape_string(strtolower($_POST['username']));
$password = mysql_real_escape_string($_POST['password']);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
checkUser($_SESSION['username'], $_SESSION['password']);
}
Then I store these $username and $password variables inside the $_SESSION and call a function checkUser($_SESSION['username'], $_SESSION['password'])); which sends two parameters. The checkUser() function executes inside lib.php
lib.php
session_start();
function checkUser($username, $password){
include "connection.php";
$result = mysqli_query($conn, "SELECT * FROM `data` WHERE `username` = '$username' AND `password` = '$password'") or die("No result".mysqli_error());
$row = mysqli_fetch_array($result);
$logic = false;
if (($row['username'] == $username) && ($row['password'] == $password)) {
$logic = true;
echo "HI,".$username;
?>
<a href='logout.php'>Log Out</a>
<?php
$file = $row['file'];
echo "<img src='images/users/".$file."' >";
}
else{
echo "Failed to login. Username or password is incorrect. Try again.";
}
}
This part is for showing the name of the user and the image according to it.
logout.php works
logout.php
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["file"]);
header("Location: index.php");
session_destroy();
The problem is when I navigate from one page to another, the $_SESSION variable becomes empty. Something is wrong with session. Please help me.
in the php pages you need to access session variable add session_start() after the starting <?php code

Using Session and Cookies together for remember me

In my login page I am using Session and Cookies both, session for usual login and cookies when remember me is checked. My code for creating session or setting cookies is:
if(isset($_POST['login'])){
$username = $_POST['user_login'];
$password = $_POST['password_login'];
$stmt = $db->prepare("SELECT * FROM userss WHERE username = :username AND password = :password");
$stmt->execute(array(':username'=>$username,':password'=>$password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$user_db = $row['username'];
$pass_db = $row['password'];
if($username == $user_db && $password == $pass_db) {
$_SESSION['username']=$username;
if ($_POST['rememberme']!=NULL) {
setcookie('username', $username,time()+31556926);
}
header("Location:main.php");
}
and then on any page to create a user fuction I am calling session or cookie like this:
if(isset($_COOKIE['username'])||isset($_SESSION['username'])) {
$username = $_COOKIE['username'];
$username = $_SESSION['username'];
}
Now my problem is:
Even when remember me is checked session is used and not cookies I tested it by exiting my browser. I can't figure out where code has gone wrong.
In the second code if(isset($_COOKIE['username'])||isset($_SESSION['username'])) { is correct but I am not sure how to define username for both different situations also
$username = $_COOKIE['username']; is giving me undefined index username. May be my way of setting cookies has gone wrong.
Replace here
if (isset($_POST['rememberme'])) {
setcookie('username', $username,time()+31556926);
}
And in user functions
if(isset($_SESSION['username']) {
$username = $_SESSION['username'];
}
else if(isset($_COOKIE['username']){
$username = $_COOKIE['username'];
}
else
{
//invalid ---
}

Verifying user login against hash stored in database

I know this one has been asked before but have not been able to find a solution on previous questions.
Secure hash and salt for PHP passwords
Password verifying against database using bcrypt
php password_verify not working with database
I'm attempting to hash the password when registering and then verify it when trying to login. The query is retrieving the password associated with the username however isn't being verified correctly.
The problem is the way I am trying to use password_verify but no matter what I'v tried the past few hours I haven't been able to get it working. If anyone could take a look and try spot what I'm doing wrong it would be a great help.
The DB column length is set to 255 and Varchar to allow the full hash entry.
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_array($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
So I know the hash being returned from the database is being set in the $stored_hash variable correctly as if I hard code the hash returned from it and compare it, login is correct. Could it be something altering the input somewhere?
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
Function is_valid_entry($inputData,$validData)
{
$inputData_array = str_split($inputData);
$validData_array = str_split($validData);
$i = 0;
while ($i < sizeof($inputData_array))
{
if (!in_array($inputData_array[$i],$validData_array))
{
return false;
}
$i++;
}
return true;
}
//User defined global variables go here
$username = "";
$ID = "";
$errorMessage = "";
$valid_chars = "abcdefghijklmnopqrstuvwxyz
1234567890";
session_start(); //start a session
if (isset($_POST['submit'])) { //submit button has been clicked
$username = $_POST['username'];
$username = trim($username); //trim any white spaces in the input value
$username = lcfirst($username); //attempts to convert upper case to lower
$username = htmlspecialchars($username); //convert special chars to html rendering null
$username = strip_tags($username); //Strip tags from input string
$ID = $_POST['ID']; //read in the value the user has entered for the password and assign to $ID
$ID = htmlspecialchars($ID);
$ID = strip_tags($ID);
$ID = trim($ID);
if (!is_numeric($ID)) { //if $ID is not numeric redirect to login page
$errorMessage = "Invalid username or password.";
$_SESSION['error'] = $errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php');
} else if (!is_valid_entry($username,$valid_chars)) { //check that user name is a valid char
$errorMessage = "Invalid username or password";
$_SESSION['error'] = errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php'); //redirect the user to the login page
} else { //if user name & $id are both valid
//now check if they are in the database
$mySQL_Server = "127.0.0.1";
$db_userName = "root";
$db_password = "";
$database = "projectdatabase";
//connect to the database on the MySQL server & store the connection in $conn
$conn = mysqli_connect($mySQL_Server, $db_userName, $db_password, $database);
if (mysqli_connect_errno($conn))
{
print("Error connecting to MySQL database: " . mysqli_connect_error($conn));
} else
{
print("Connected to the MySQL database");
}
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_assoc($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "$ID, $stored_hash"; //test to ensure is reaching this statement
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
mysqli_close($conn);
}
}
?>

How to set user/admin accounts for a redirect after log in? PHP

My problem with this code is that the IF statement which is deciding what page to go to seems to default to index.php. I have made a login table in MySQL already and have username/password column, and another column with a boolean value which states if the user is admin.
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$count = mysql_num_rows($result);
$auth = $row['admin'];
if ($count == 1) {
if ($auth['admin'] == 1) {
session_start();
$_SESSION['admin'] = $auth;
$_SESSION['username'] = $username;
header("location: member.php");
} elseif ($auth['admin'] == 0) {
session_start();
$_SESSION['admin'] = $auth;
header("location:index.php");
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Since you already extracted your admin value here:
$auth=$row['admin'];
You don't have to extract it here:
if($auth['admin']==1){
or here:
elseif($auth['admin']==0){
This simple change should fix your problem:
if($auth==1) {
...
} elseif($auth==0) {
...
In your original code, $auth['admin'] doesn't exist because $auth itself is just an integer, so it will pass the $auth['admin'] == 0 test since it is "falsy."
Also, it looks like you may have a case where $auth is completely undefined, in which case you should use "strict comparison" for that second condition, so you're looking for an actual zero and not just anything falsy:
} elseif($auth===0) {
I re wrote your login script. Try this. I think you'll find this will work much better for what your doing.
if(isset($_POST['username'])) {
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$password = $_POST['password'];
//$password = md5($password);
$db_host = "host"; $db_username = "username"; $db_pass = "password"; $db_name = "db_name"; mysql_connect("$db_host","$db_username","$db_pass"); mysql_select_db("$db_name"); // connect to your database only if username is set
$sql = mysql_query("SELECT * FROM login WHERE username='$username' and password='$password'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){ // if the user exists run while loop below
session_start(); // start session here (only once)
while($row = mysql_fetch_array($sql)){ // fetch the users admin from query
$auth = $row['admin'];
$_SESSION['admin'] = $auth; // set admin session variable
$_SESSION['username'] = $username; // set username session variable
if($auth == 1){
header("location: member.php"); // if user auth is 1, send to member
}else if($auth == 0){
header("location: index.php"); // if user auth is 0, send to index
}
exit();
}
} else {
header('Location: login.php'); // if user doesnt exist, reload login page.
}
mysql_close();
}
I recommend using md5 hash passwords.
When a person registers at your site, you can convert the password to md5 hash with this line $password = md5($password); prior to the db entry
Regarding your $auth above, this assumes your entry in the database is either a 0 or a 1. If you are controlling it this way, i recommend using enum in the sql database. set the type to "enum" and the type to '0', '1'
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result=mysql_query($query) or die(mysql_error());
$row= mysql_fetch_array($result);
$count=mysql_num_rows($result);
$auth= (int)$row['admin'];
if($count){
if($auth == 1){
$_SESSION['admin']= $auth;
$_SESSION['username']= $username;
header("location: member.php");
exit;
}elseif($auth == 0){
$_SESSION['admin']= $auth;
header("location:index.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
Try
header("Location: index.php");
exit;
header("Location: member.php");
exit;
Note the Capital L and the exit;
Also try if($auth == "1") and elseif($auth == "0") respectively.
If you value the security of your login page, use PDO or mysqli instead of mysql. It is deprecated and insecure due to its vulnerability to SQL injection.
Also, take advantage of PhP's password_hash and password_verifywhen handling storage and verification of passwords. It is a lot more secure compared to md5(). If you'd like examples of usage, let me know.

Categories