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

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.

Related

Login / Logout Session Issue

I am creating some kind of a login/registration system right now. Registration form, email confirmation and login is already working. I now have problems with my sessions. Please keep in mind that this project is just a test project. I know that I should use PDO but for this testing purposes I need to find out why it is not working they way I did it.
Here is my login.php PHP code:
<?php include ('inc/database.php');
if (isset($_POST['submit'])) {
// Initialize a session:
session_start();
$error = array();//this aaray will store all error messages
if (empty($_POST['email'])) {//if the email supplied is empty
$error[] = 'You forgot to enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])) {
$Email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwort'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['passwort'];
}
if (empty($error))//if the array is empty , it means no error found
{
$query_check_credentials = "SELECT * FROM user WHERE email='$Email' AND password='$Password' AND activation IS NULL";
$result_check_credentials = mysqli_query($connect, $query_check_credentials);
if(!$result_check_credentials){//If the QUery Failed
echo 'Query Failed ';
}
if (#mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
{ // A match was made.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
//Assign the result of this query to SESSION Global Variable
header("Location: index.php");
}else
{ $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
}
} else {
echo '<div> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
if(isset($msg_error)){
echo '<div>'.$msg_error.' </div>';
}
/// var_dump($error);
} // End of the main Submit conditional.
?>
Here is the beginning of my protected index.php
<?php
ob_start();
session_start();
if(!isset($_SESSION['email'])){
header("Location: login.php");
}
include 'header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
.....
There must be a problem with my session and I do not know why. Is it wrong to use the email as session? Am I using the email as session? What other options do I have?
Problem is right now, that if I click on Login, nothing happens. I will be redirected to login.php instead of index.php!
Any suggestions?
As Fred -ii- already mentioned in comments above, your $_SESSION['email'] is never set, and therefor you are re-directed to your login-page every time.
It's also worth noting that when using header("Location: ...");, you can not have any output prior to the header! Otherwise the header will fail. Output is generally any HTML, echo, whitespace (see this SO).
So, once you make sure that your header("Location: index.php"); actually works, move on to fixing your $_SESSION.
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC); does not set $_SESSION['email'] (as already stated by Fred -ii-). To fix this, you need to fix your results from the database.
$row = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email'] = $row["email"];
The code above will return the row "email" from the result in the database, and set it to the session of "email", which later is checked when you are trying to access index.php.
A couple of side-pointers (not really your current problem, but a few tips to make your code better).
You should use exit; after using header("Location: ..."); (See this SO)
You are not hashing your password, so it's stored in plain-text in your database (big no-no)
Indenting your code properly makes it a lot easier to read, and in turn easier to troubleshoot
If you do the above, and it still doesn't work, we'd need some more information to help troubleshoot further (like what happens when you're logging in (is it as expected?), what results are returned, and so forth).
try to change,
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
to
$results = mysqli_fetch_row($result_check_credentials, MYSQLI_ASSOC);
$_SESSION['email']=$results['email'];
and try to check your "activation" field in database for null while login...

Redirecting to another page, using variables from the first one

I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();

Redirecting logged in users

I have created profiles for users so that when a user logs in they are redirected to their own profile page.
login.php (relevant code only)
$MemberID = user_id_from_username($username);
$_SESSION['MemberID'] = $username;
header('location: member.php?username='.$username);
member.php
if (logged_in () === true){
echo "Welcome, ".$_SESSION['MemberID']. "!<br><a href='logout.php'>Logout</a>\n<a href='index.php'>Back to homepage</a></p>";
}
if(isset($_GET['username']) === true & empty ($_GET['username']) === false) {
$username = $_GET ['username'];
//check if user actually exisits
if (user_exists($username) === true) {
//get username from user id
$MemberID = user_id_from_username($username);
$profile_data =user_data($MemberID,'Name','Address','Postcode','DOB','Mobile','CoinsAvailable','Email','profile','OddJobName','Description','CoinValue','DaysAvailable');//Need to pull out stuff from oddjob table
echo $MemberID;
}else{
protect_page();
}
}
relevant functions:
function user_data($MemberID){ //pass in memberid to get info about user
$data = array();//data to be returned
$MemberID =(int)$MemberID;//creating int from this input
$func_num_args = func_num_args(); //count number of arguments from user data on init.php
$func_get_args = func_get_args();
if ($func_num_args >1) { //if more then 1, unset the first element of array
unset($func_get_args[0]);
$fields = '`' . implode('`,`', $func_get_args) . '`'; //taking array and converting to string
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `member`,`oddjob` WHERE member.MemberID = oddjob.MemberID AND member.MemberID = $MemberID"))or die (mysql_error());
//echo $MemberID;
return $data;
}
}
function logged_in() {
return (isset($_SESSION['MemberID'])) ? true : false; //Email
}
if (logged_in() ===true) {
$session_MemberID = $_SESSION['MemberID'];//grabbing value from login
$user_data= user_data($session_MemberID,'MemberID','Name','Address','Postcode','DOB','Mobile','CoinsAvailable','Email','Password','RepeatPassword','OddJobName','Description','DaysAvailable','profile');
exit();
}
All this code allows the user to be redirected to their own page, when they login their name is displayed along with other $profile_data information. Now I want the user to be able to update their own info by clicking on a link to update_info.php. But I don't know how to get the members username to appear in the URL when they visit update_info.php like it does when they log in.
In the member page (where the link is) I tried:
<a><?php header('location:update_info.php?username='.$username)?>">Update info</a></p>
But now when the user logs in they are redirected to update_info.php instead of member.php. Can anybody tell me how to fix this? Thanks.
Do you mean:
Update info
This passes the $username to the update_info.php page
Maybe you wanted to write this?
Update info</p>
All right.
Lets explain the basics on how to build a -basic- authentication. And then extend it to a safe one :)
1 - user logs in : You check the database if the credentials are allright.
If Yes -> $_SESSION['loggedIn'] = true;
2 - On every page you want to check if the person is logged in; you put a check:
if(!$_SESSION['loggedIn']) { header('location:login.php');}
Some food for thought:
You don't want to store 'just' a boolean on the clientside to check if logged in. You better generate a random session-id-string. Store this in a database and store this id in the $_SESSION['loggedin']. Instead of the simple check of the value of $_SESSION['loggedIn'] you now look up the stored session ID in the database for existince and availability.
Post Scriptum:
Don't nest functions in functions in functions.
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROMmember,oddjobWHERE member.MemberID = oddjob.MemberID AND member.MemberID = $MemberID"))or die (mysql_error());
This is not readable for us, but especially not for you. You better write it like this:
$sql = "SELECT $fields FROMmember,oddjobWHERE member.MemberID = oddjob.MemberID AND member.MemberID = $MemberID";
$res = mysql_query($sql) or die(mysql_error());
$data = mysql_fetch_assoc($res);
Post Post Scriptum:
Stop using the mysql_* functions in php. See the red box on this website? These functions are not supported anymore. And you better start using PDO; which by the way has also some checking (mysql injection) standard build in; and much more!

Session not being saved after logging in

Another attempt at designing a user membership. Got to log in successfully, finds the data in the database. But in my index file, after logging in, it should check if I'm logged in and display links to my account instead of register and login. Here's the code:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
And here is the login form code, where I think the problem is because it's not storing my session id:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
Once again I'm following someone's tutorial and trying to implement it to my website and this would be perfect if it worked. Please advice why the $toplinks aren't being set after logging in.
I think the problem is, that you have to include the session_start() in every file where you want to use your session. Otherwise its working in the file like a normal array but not global. In your form i can't see that you start your session.
Edit: You need this only if you have 2 files. When you have only one file and include the other page its working when you include in once on top.
If you want to log out, then you should create a logout file, and include
session_destroy();
probably add also a href to get redirection link by doing something like:
header('location:index.php'); // will return you to index as soon as you logout.

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