Passing $_SESSION in php - php

Currently been at this for few hours now and desperately need a fresh set of eyes. When log in takes place a form is loaded to test encrypted password and username against the database, as it stands there are no errors showing up in the form when it is run but simply when it is run it denies the data from the user currently in the database being passed through.
I also recieve the final else statement giving me "Access Denied" any help would be hugely appreciated just need a fresh set of eyes, thanks alot. also to add all the $data instances are fields within the database
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$databaseName = "filestackusers";
$connect = new PDO("mysql:host=$serverName;dbname=$databaseName",$username, $password);
//encrypt pass and user for search
if(isset($_POST["username"]) && isset($_POST["password"]))
{
$FolderEncryption = md5($_POST['username']);
$passwordEncryption = md5($_POST['password']);
}
else
{
echo "information not passed";
}
try
{
//search if found load info
$checkSqlStmt = $connect->prepare("SELECT * FROM users WHERE user_folder =
:FolderEncryption AND password = :passwordEncryption");
//bind
$checkSqlStmt->bindParam(':FolderEncryption', $FolderEncryption, PDO::PARAM_STR);
$checkSqlStmt->bindParam(':passwordEncryption', $passwordEncryption, PDO::PARAM_STR);
//execute
$checkSqlStmt->execute();
$data = $checkSqlStmt -> fetchAll();
}
catch (Exception $ex)
{
die("An error has occured! " . $ex->getMessage());
}
if ($data)
{
if($_POST["username"] == $data[0]["username"]) //recheck email security
{
echo 'Access Granted';
$_SESSION['userID'] = $data[0]['user_id'];
$_SESSION['Username'] = $data[0]['username']; //set sessions
$_SESSION['Password'] = $data[0]['password'];
$_SESSION['Email'] = $data[0]['email'];
$_SESSION['UserFolder'] = $data[0]['user_folder'];
//load user info
loadFileInformation();
}
}
else
{
echo "Access Denied";
}
?>

You only echo access denied when $data evaluates to false. That can be the case when you don't assign it at all, which happens when you get an exception when executing the query. If there is no exception, fetchAll might still return false in case of an error.
But also, if the query executes correctly but returns no rows, fetchAll() returns an empty array, which also evaluates to false in PHP. (I don't make this stuff up!)
So whichever the case, it is due to the execution of the query.

Chances are that your $data variable is false so your code is echoing "Access Denied". You should set your condition to check that $data equals what you want it to and then proceed.
For Example:
if ($data == "Blah"){
if($_POST["username"] == $data[0]["username"]) //recheck email security
{
//Blah Blah
}
}else{echo "Access Denied";}
As opposed to:
if ($data)
{
if($_POST["username"] == $data[0]["username"]) //recheck email security
{
//Blah Blah
}
}else{echo "Access Denied";} // etc
The point is that your condition should be more precises. Whether using fetchAll or what ever.

Related

Username and Password Don't Match Output

I am in the process of creating a signup system using mysql and PHP. I have been able to connect the system to a database and it works for when the username and password entered are correct. However, when the username and password is not correct (i.e anytime when the username/password pair is not stored in the database), it just leads to a blank white page. Currently, my code has it so that when the username and password are not correct, it prints our "Invalid username of password". Please see the code below, any help is appreciated. Thank you in advance!
<?php
require_once 'source/session.php';
require_once 'source/db_connect.php';
if(isset($_POST['login-btn'])) {
$user = $_POST['user-name'];
$password = $_POST['user-pass'];
try {
$SQLQuery = "SELECT * FROM users WHERE username = :username";
$statement = $conn->prepare($SQLQuery);
$statement->execute(array(':username' => $user));
while($row = $statement->fetch()) {
$id = $row['id'];
$hashed_password = $row['password'];
$username = $row['username'];
if(password_verify($password, $hashed_password)) {
$_SESSION['id'] = $id;
$_SESSION['username'] = $username;
header('location: dashboard.php');
}
else {
echo "Error: Invalid username or password";
}
}
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
Well, currently your SQL query would return a set with 0 rows for a non-existent user, but that would not cause an error. It would just be an empty result set. Therefore it would not go through the while loop, it would just terminate without an error.
Your logic is leaving out the check to see whether $statement->rowCount() is zero.
To clarify in case this answer is confusing: You have 0 results if you enter a username that doesn't exist... then you do while(0) so you never get into that part of the code. No password check is done. And no error is thrown, so you never escape the try{} and get into the catch{} portion of the code. There is nothing returned here if the username turns up zero results from the database. You need to add another error in that case.

$_Session variables not accessible on the same page they are created

My issue is that for some reason on the login.php page of my website, I initialize some $_Session Variables from my users table in the corresponding database, but while these variables seem to function properly on other pages I can't do anything with them immediately after initializing them, because they don't seem to exist. This is an issue because I would like to reference the variables I have defined to create other session variables for efficiency, and because I would like to use it for a welcome message like the simple example shown in my code. Here is the code in question:
if(isset($_POST['user_email']) && !empty($_POST['user_email']) AND isset($_POST['user_pass']) && !empty($_POST['user_pass']))
{
$email = mysqli_real_escape_string($link, $_POST['user_email']); // Set variable for the username
$password = mysqli_real_escape_string($link, sha1($_POST['user_pass'])); // Set variable for the password and convert it to an sha1 hash.
$result = mysqli_query($link, "SELECT user_email, user_pass, user_active FROM users WHERE user_email='".$email."' AND user_pass='".$password."' AND user_active='1'") or die(mysqli_error($link));
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_uuid'] = $row['user_uuid'];
$_SESSION['user_level'] = $row['user_level'];
$_SESSION['user_rank'] = $row['user_level'];
}
echo 'Welcome, ' . $_SESSION['user_uuid'] . '. <br />Proceed to the forum overview.';
}
}
}
I have session_start(); at the top of my connect.php which is included at the top of the signin.php doc.
The result of this code on this page is something like:
Welcome, .
Proceed to the forum overview.
However if I run it on a different page on the site it properly prints, i.e.:
Welcome, username.
Proceed to the forum overview
Thanks.

Can't enter the home page, always directing back to login page

As this page is owned by it users, so it has each credentials to enter it which it is by using login form of php (that's what I know so far, I am not very good in php, to be honest).
The problem I do really guess about this must be in the using of session function (and this is the most complicated things to me know, I am not very familiar of using this.)
In the config of the form, I set the session like this (Well, I just copy paste the code from somewhhere) as follow:
// User Redirect Conditions will go here
if($count==1)
{
// Save type and other information in Session for future use.
$_SESSION[type]=$row[0];
$_SESSION[Region]=$row[1];
$_SESSION[myemail]=$myemail;
// if user type is ACTAdmin only then he can access protected page.
if($row[0] == 'ACTAdmin') {
header( "location:index.php");
}
else {
header( "location:login.html");
}
}
else
{
header("location:login.html");
}
// Closing MySQL database connection
$dbh = null;
In the head of the home page (and in each all related pages), I write a session start there like this:
<?php
include('UserSessionAdmin.php');
?>
In which it will get the data from UserSessionAdmin.php:
<?php
session_start();
if($_SESSION[type]!='ACTAdmin'){
header('location:login.html');
exit();
}
include('configPDO.php');
?>
What is included in the configPDO.php is here:
<?php
// mysql hostname
$hostname = 'mysql.com';
// mysql username
$username = 'alkushh';
// mysql password
$password = 'alkush';
// Database Connection using PDO
try {
$dbh = new PDO("mysql:host=$hostname;dbname=user", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
It's been more than two days for me just to solve it but I don't have any idea how to. Some people who are experts in here may help me with this thing, please.
Thank you and regards,
Here is the full script that define the $count==1
<?php
// Start Session because we will save some values to session varaible.
session_start();
// include connection file
include("configPDO.php");
// Define $myusername and $mypassword
$myemail=$_POST['myemail'];
$mypassword=$_POST['mypassword'];
// We Will prepare SQL Query
$STM = $dbh->prepare("SELECT Type,Region FROM user WHERE myemail = :myemail AND mypassword = :mypassword");
// bind paramenters, Named paramenters alaways start with colon(:)
$STM->bindParam(':myemail', $myemail);
$STM->bindParam(':mypassword', $mypassword);
// For Executing prepared statement we will use below function
$STM->execute();
// Count no. of records
$count = $STM->rowCount();
//just fetch. only gets one row. So no foreach loop needed :)
$row = $STM -> fetch();
// User Redirect Conditions will go here
if($count==1)
.....
.....
Here it is
if ( $count == 1 ) {
$_SESSION['login_id'] = $row['id']; // i prefer to name it login_id, you can use $row['id'] or $row[0]. but i prefer to write with the column name
if ( $_SESSION['login_id'] == 1 ) { // it means if login id = 1 then go to index.php
header("location: index.php");
} else {
header("location: login.html");
}
}
else { header("location: login.html"); }
i cut session region because you didnt have a region column and also i cut session myemail because you didnt need it
UserSessionAdmin.php
<?php
session_start();
if ( $_SESSION['login_id'] == 0 || $_SESSION['login_id'] == '' ) {
header('location: login.html');
exit();
}
require_once('configPDO.php');
?>
Please turn on your error reporting to see, that there is no constants such as type, Region, myemail. Use " or ' around parameter of session:
if (strcmp($_SESSION['type'], 'ACTAdmin') !== 0) {
header('location:login.html');
exit();
}

PHP UserName and Password Validation Check

I'm creating a login page where the user name and password are entered and then checked against the database to see if they match (I have posted on this previously but my code was completely incorrect so I had to start over) Upon clicking the submit button the user should be directed to the homepage (index.php) if the two values match up or an error message should appear stating "Invalid login. Please try again." Very simple basic stuff. Yet, I cannot get any variation to work.
Here is my code without the validation check. I believe this code is right but, if not, could someone please explain as to why. I am not asking anyone to write any code, just explain why it is not working properly.
<?php
function Password($UserName)
{
//database login
$dsn = 'mysql:host=XXX;dbname=XXX';
$username='*****';
$password='*****';
//variable for errors
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
//try to run code
try {
//object to open database
$db = new PDO($dsn,$username,$password, $options);
//check username against password
$SQL = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME");
$SQL->bindValue(':USER_NAME', $UserName);
$SQL->execute();
$username = $SQL->fetch();
if($username === false)
{
$Password = null;
}
else
{
$Password = $username['USER_PASSWORD'];
}
return $Password;
$SQL->closeCursor();
$db = null;
} catch(PDOException $e){
$error_message = $e->getMessage();
echo("<p>Database Error: $error_message</p>");
exit();
}
?>
Now the validation code. I've googled this and found several hundred ways to do so but this method most closely matches my coding style. It is incomplete and I would like some help as to how to finish it properly and then where to place it within the code above. My assumption is right after this comment: "//check username against password". Now I've seen this version twice and in one version the check is for txtUserName and the other is just username. I believe there should be else statements after each if statement to direct them to the index.php page. Also, the third if statement is the check to see if the password matches the username. No variation of this did I understand. They were far too complex.
function Login()
{
if(empty($_POST['txtUserName']))
{
$this->HandleError("UserName is empty!");
return false;
}
if(empty($_POST['txtPassword']))
{
$this->HandleError("Password is empty!");
return false;
}
$username = trim($_POST['txtUserName']);
$password = trim($_POST['txtPassword']);
if(!$this->($username,$password))
{
return false;
}
}
I know I am asking a lot here. But I am very new to PHP and am really trying hard to learn it. And there is way too much info out there and most of it is not for beginners. Any, and all, help would be greatly appreciated.
To begin with, let's assume that we have a PDO connection, just like you do already, for example with this function:
You can do something like:
// Usage: $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(Exception $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
So that you can have a database connection like this:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
$db = connectToDataBase($host, $databaseName, $user, $pass);
So far we have the same stuff as you.
Now, I assume that we're on a PHP page where the user submitted his username and password, to begin with: check if we really received the username and the password, with the ternary oprator:
// receive parameters to log in with.
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
Now you can validate if those inputs were actually posted:
// Check if all required parameters are set and make sure
// that a user is not logged in already
if(isset($_SESSION['loggedIn']))
{
// You don't want an already logged in user to try to log in.
$alrLogged = "You're already logged in.";
$_SESSION['warningMessage'] = $alrLogged;
header("Location: ../index.php");
}
else if($userName && $password)
{
// Verify an user by the email address and password
// submitted to this page
verifyUser($userName, $password, $db);
}
else if($userName && (!($password)))
{
$noPass = "You didn't fill out your password.";
$_SESSION['warningMessage'] = $noPass;
header("Location: ../index.php");
}
else if((!$userName) && $password)
{
$noUserName = "You didn't fill out your user name.";
$_SESSION['warningMessage'] = $noUserName;
header("Location: ../index.php");
}
else if((!$userName) && (!($password)))
{
$neither = "You didn't fill out your user name nor did you fill out your password.";
$_SESSION['warningMessage'] = $neither;
header("Location: ../index.php");
}
else
{
$unknownError = "An unknown error occurred.". NL. "Try again or <a href='../sites/contact.php' title='Contact us' target='_blank'>contact us</a>.";
$_SESSION['warningMessage'] = $unknownError;
header("Location: ../index.php");
}
Now, let's assume that everything went well and you already have a database connection stored in the variable $db, then you can work with the function
verifyUser($userName, $password, $db);
Like already mentioned in the first else if statement:
// Usage: verifyUser($userName, $password, $db);
// Pre: $db has already been defined and is a reference
// to a PDO connection.
// $userName is of type string.
// $password is of type string.
// Post: $user exists and has been granted a session that declares
// the fact that he is logged in.
function verifyUser($userName, $password, $db)
{
$userExists = userExists($userName, $db); // Check if user exists with that username.
if(!($user))
{
// User not found.
// Create warning message.
$notFound= "User not found.";
$_SESSION['warningMessage'] = $notFound;
header("Location: ../index.php");
}
else
{
// The user exists, here you can use your smart function which receives
// the hash of the password of the user:
$passwordHash = Password($UserName);
// If you have PHPass, an awesome hashing library for PHP
// http://www.openwall.com/phpass/
// Then you can do this:
$passwordMatch = PHPhassMatch($passwordHash , $password);
// Or you can just create a basic functions which does the same;
// Receive 1 parameter which is a hashed password, one which is not hashed,
// so you hash the second one and check if the hashes match.
if($passwordMatch)
{
// The user exists and he entered the correct password.
$_SESSION['isLoggedIn'] = true;
header("Location: ../index.php");
// Whatever more you want to do.
}
else
{
// Password incorrect.
// Create warning message.
$wrongPass = "Username or password incorrect."; // Don't give to much info.
$_SESSION['warningMessage'] = $wrongPass;
header("Location: ../index.php");
}
}
}
And the function userExists($userName, $db) can be like:
function userExists($userName, $db)
{
$stmt = $db->prepare("SELECT * FROM users WHERE USER_NAME = :USER_NAME;");
$stmt->execute(array(":USER_NAME "=>$userName));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
// User exists.
return true;
}
// User doesn't exist.
return false;
}
Where the function Password is like:
function Password($UserName)
{
$stmt = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME;");
$stmt->execute(array(":USER_NAME"=>UserName));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['USER_PASSWORD'];
}
// No result.
return false;
}
Again, make sure you're not matching plain text passwords, or basic shai1, md5 encryptiones etc. I really recommend that you take a look at PHPass.
I hope I'm making myself clear.

Mysql result to set session variable

I want to use the result of a mysql query to set a session variable however at present I am struggling to make it set.
My code I have is:
<?php
ob_start("ob_gzhandler");
?>
<?php
// Include required MySQL configuration file and functions
require_once('config.inc.php');
require_once('functions.inc.php');
// Start session
session_start();
// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
// If user is already logged in, redirect to main page
redirect('../index.php');
} else {
// Make sure that user submitted a username/password and username only consists of alphanumeric chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
(!ctype_alnum($_POST['username'])) ) {
redirect('../login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if (mysqli_connect_errno()) {
printf("Unable to connect to database: %s", mysqli_connect_error());
exit();
}
// Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// Construct SQL statement for query & execute
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
redirect('../index.php');
} else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
}
?>
I am then testing the session variables with:
<?php
session_start();
echo "Login Status is:".$_SESSION['logged_in'];
echo "<br/>";
echo "Auth status is level:".$_SESSION['auth_lvl'];
?>
On my testing page the session logged in works fine displaying the correct information however the auth lvl variable displays nothing.
I can only assume that I am not calling the information correctly that I am setting the variable with in the first place.
Any help would be appreciated.
Alan.
Something I have notice and I have been trying the suggestions is that if I set a definative rather than trying to retreive a value from the database that value will return on my test page. i.e.
$_SESSION['auth_lvl'] = 'test';
This tells me it is the way in which I am pulling the data from the database and trying to set it as $_SESSION['auth_lvl'] that is causing the problem.
Found the problem.
the code read:
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// ADD THIS SET OF LINES
$data = mysql_fetch_assoc( $result );
// Replace auth_lvl with the name of your database column name
$Auth_lvl = $data['Auth_lvl'];
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
Because I had used mysqli on this code I had not notice that on the //ADD THIS SET OF LINES piece of code that an 'i' was missing. When I changed the code to:
$data = mysqli_fetch_assoc( $result );
Everything fired into life.
Thanks for your help guys.
I can't see anywhere that you have assigned $Auth_lvl with a value, so when you do:
$_SESSION['auth_lvl'] = $Auth_lvl;
It's presumably getting assigned null.
I'm not seeing where you are setting $Auth_lvl. After you check for the results being there, and rows, you're going straight to setting a session variable against an empty variable.
if (is_object($result) && $result->num_rows == 1) {
// ADD THIS SET OF LINES
$data = mysql_fetch_assoc( $result );
// Replace auth_lvl with the name of your database column name
$Auth_lvl = $data['auth_lvl']'
// Set session variable for login status to true
$_SESSION['auth_lvl'] = $Auth_lvl;
$_SESSION['logged_in'] = true;
redirect('../index.php');
Then with your logged_in session variable, you're setting it as a boolean, true, and then trying to echo it out as normal text.
if ( $_SESSION['logged_in'] ) { echo "Login status is: True"; }
I hope that helps.
-Dan

Categories