cannot pass session variables - php

if(isset($_POST["username"])&& isset($_POST["password"])){
include('config.php'); //this one connects to the database
$username = $_POST["username"];
$password = md5($_POST["password"]);
$sql2=mysql_query("SELECT * FROM clinic_staff WHERE username='$username' AND password='$password'");
$count2 = mysql_num_rows($sql2);
if($count2 == 1){
while($row2 = mysql_fetch_array($sql2)){
$id = $row2["staff_ID"];
$position = $row2["position"];
}
$_SESSION["id"] = $id;
$_SESSION["name"] = $username;
$_SESSION["password"] = $password;
$_SESSION["pos"] = $position;
header("location:index.php");
exit();
}
The problem is I can't echo the username in index.php. I don't know if it is passed successfully. in index.php i used echo $_SESSION["name"];

put session_start(); at the beginning of your document with no white space above it.

You need to look at session_start to start a session. Examples are here

I don't see session_start();. You have to call that function at the top of every page you use session variables. (At least I have to do that on my server, somebody said to me you should actually be able to use Session variables without session_start();, but everything that needed a session variable stopped working after I removed the calls to session_start();)

Related

Save user information in SESSION not working .PHP

so am on way to save user data into session. I have set up first username and memberID which looks like working properly. but once I have added more details to save session won't read them in othter pages. Session starts in database connection. I don't know where is problem and hope for help from you guys. Thanks
if (password_verify($password, $row['password'])) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['email'] = $row['email'];
$_SESSION['avatar'] = $row['avatar'];
$_SESSION['loggedin_time'] = time();
return true;
}
Code I'am adding in php page:
<?php echo htmlspecialchars($_SESSION['email'], ENT_QUOTES); ?>
FIXED
My statement had only selecting memberID and username!!!
Always remember to use session_start(), to set or use it. Remember to do it in the top of your .PHP file.
First php page
session_start();
if (password_verify($password, $row['password'])) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['email'] = $row['email'];
$_SESSION['avatar'] = $row['avatar'];
$_SESSION['loggedin_time'] = time();
return true;
}
Another php page
session_start();
...
Note: if this isn't the case, you should try to do a var_dump() on the two variables, and see if there is any information stored in them.
Fixed.
Problem was that I had statement to select only memberID and username in my PDO!!!

SESSION variable wont continue to next page

Even though I have searched and forums I am failing to get a Session Variable to continue to the next page.
Every page has session_start(). Each Header has exit() after it.
If I add a new member the SESSION Variable is fine. But when I log on the SESSION Variable gets lost after login.
Here is the code for the Login Page. Everything works except for the SESSION variable wont parse to the next page. What am I missing? oh and the code is a bit messy a bit like my workstation.
<?php
session_start();
//Connection to DB in the usual way with check to DB
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
//hacking protection in the usual way
$sql = "SELECT * FROM table WHERE `u_password` = '$mypassword' AND `user` = '$myusername' ";
$result = mysqli_query($mdb, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
$ls = "Online";
$datenow = date("Y-m-d H:i:s");
$id = $row['id'];
$usql = "UPDATE addnewmbr SET loggedstatus = '$ls', logindate = '$datenow' WHERE id = '$id'";
if (mysqli_query($mdb, $usql)) {
$_SESSION["user_id"] = $row['id']; //this variable is lost on next page
$_SESSION["user"] = $row['user']; //this variable is lost on next page
$_SESSION["gender"] = $row['gender']; //this variable is lost on next page
if ($_SESSION['gender'] == "man") {
header('Location: newpage.php');
exit(); // the redirection $_SESSION['gender'] works so the variable is set
} else {
header('Location: anotherpage.php');
exit();
}
} else {
header('Location: back to indexpage.html');
exit();
}
?>
anotherpage.php
<?php
session_start();
echo $_SESSION["user"];
?>
result on this page after Vardump on test page
array(0) { }
Apart from you being vulnerable for SQL injections (preventable by preparing your statements, binding your values and executing it)
Why do you set $_SESSION["user"] equal to $row['user'] and not to $myusername?
In this case, they are the same since you fetch the row where user = $myusername
Not sure if that solves anything.
It was an easy fix after all.... For all that get stuck with SESSION variables being lost!
on the header just be careful..... remove the www from the header
e.g.
SESSION problem
header('Location: http://www.website.php');
SESSION fix
header('Location: http://website.php');
That's all there is to it.

PHP Session ending automatically

I do a lot of work using PHP frameworks but I am now building a simple login system from scratch and I am stumped. I am using PDO for my database queries. I have a simple login form which points to the same page using $_SERVER['PHP_SELF']. Then I have this code...
<?php
//LOG IN
if($_POST['login_submit']){
$username = $_POST['username'];
$password = $_POST['password'];
//Query
$database->query("SELECT * FROM users WHERE username = :username AND password = :password");
$database->bind(':username',$username);
$database->bind(':password',$password);
$rows = $database->resultset();
$count = count($rows);
if($count > 0){
session_start();
//Assign session variables
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['logged_in'] = 1;
} else {
$login_msg[] = 'Sorry, that login does not work';
}
}
When I login, its fine. It starts the session. But as soon as I go to another page the session is broken. I suspect maybe cause the session_start() is in the if($_POST['login_submit']) condition. But I could sware Ive done it like this before. Any help would be awesome..thanks!
The first line of your code...
if($_POST['login_submit']){
Only, if you submit your login form, the session is started.
And, on all other pages, you have to call session_start() ...

Displaying username using $_SESSION['username']

When I try to display the username of a logged-in user I get 'Welcome, 1' where 1 should be the username of the person logged in.
This is my code in the members.php. The commented out line doesn't work either.
<?php
require_once('include.php');
?>
<?php
// echo "welcome, {$_SESSION['username']}";
$user = $_SESSION['username'];
echo "Welcome $user";
?>
The user is logged in, I wonder if I've made a mistake in the check-login page.
The code for the check_login page is:
<?php
require_once('include.php');
$username = trim($_POST['user']);
$password = trim($_POST['pass']);
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM user WHERE username='$username' and password='$password';";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count !== 0){
$_SESSION['logged-in'] = true;
header("location:members.php?user=$username");
exit;
}
else {
$_SESSION['logged-in'] = false;
header("location:login_again.php");
exit;
}
?>
which redirects to the members.php page upon successful login.
Anybody have any ideas why the username is '1' everytime?
Many thanks
there needs to be a session_start() somewhere at the top of your code
<?php session_start();
require_once('include.php');
?>
<?php
// echo "welcome, {$_SESSION['username']}";
$user = $_SESSION['username'];
echo "Welcome $user";
?>
you also need to set it before accessing it with session_start at the top of this file also
if($count>0){
$_SESSION['username']=$username;
$_SESSION['logged-in'] = true;
header("location:members.php?user=$username");
exit;
}
your code is open for sql injection attacks, Use prepared statements instead
In your check_login page I don't see either session_start and the code for saving username into session so that you can retrieve it on the other page.
In check_login page please add:
session_start();
at the start and then set:
$_SESSION['username'] = $username;
so that you can retrieve and display it on the other page.
Please check following points.
Make sure you set username in the Session variable.
From your code, I do not see any line like following:
$_SESSION['username'] = $username
Without setting, you can get nothing.
If you did session_start() before using $_SESSION variable.
session_start() is required function to be called if you gonna use $_SESSION variable.

Trouble storing a session variable

I have a log in script that currently stores 2 variables a valid variable and a username variable. I am now trying to add in a name variable so I have altered the MySQL query to get the name from the database and have tried to store the name in a session variable but for some reason its just not storing it. Probably best just to show you the script, I have been studying PHP for only 2 months so I really appreciate your help.
<?php
ob_start(); // Start output buffering
session_start(); //must call session_start before using any $_SESSION variables3
$_SESSION['username'] = $username;
function validateUser($username)
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
$_SESSION['name'] = $userData['name'];
}
$username = isset($_POST['username'])?$_POST['username']:'';
$password = isset($_POST['password'])?$_POST['password']:'';
//connect to the database here
$hostname_Takeaway = "localhost";
$database_Takeaway = "diningtime";
$username_Takeaway = "root";
$password_Takeaway = "root";
$Takeaway = mysql_pconnect($hostname_Takeaway, $username_Takeaway, $password_Takeaway) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_Takeaway, $Takeaway);
$username = mysql_real_escape_string($username);
$query = "SELECT name, 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/diningtime/admin-home.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/diningtime/admin-home.php?login=fail');
die();
}
else
{
validateUser($username); //sets the session data for this user
}
//redirect to another page or display "login success" message
header('Location: http://localhost/diningtime/main');
die();
//redirect to another page or display "login success" message
?>
Your validateUser() function does not have a $userData variable in scope, so you're assigning NULL to $_SESSION['name'].
Either make $userData be a global so it becomes visible in the function's scope, or pass it as an argument:
function validateUser($user, $userData) {
^^^^^^^^^-- pass as arg
global $userData;
^^^^^^^^^^^^^^^^^--- bring var in-scope
...
$_SESSION['name'] = $GLOBALS['userData']['name'];
^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- refer to global scope
}
Any one of these 3 options would solve the problem (just don't do all three at the same time)
Your validateUser function doesn't get values from $userData array, you need to have another agument in it, like
function validateUser($username, $name)
and then pass those values from your code, or you could move the mysql authentication inside this function and then it will work. Generally, a function doesn't recognize any variable which you define outside of that function.
P.S. What should the fifth line
$_SESSION['username'] = $username;
do? I'm suspecting it from being utterly useless in that place :-)
Lots of mistakes here.
<?php
ob_start(); // Start output buffering
session_start(); //must call session_start before using any $_SESSION variables3
$_SESSION['username'] = $username;
from where $username came?
$username = isset($_POST['username'])?$_POST['username']:'';
$password = isset($_POST['password'])?$_POST['password']:'';
Now you are checking for its existance.
$Takeaway = mysql_pconnect($hostname_Takeaway, $username_Takeaway, $password_Takeaway) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_Takeaway, $Takeaway);
mysql_* deprecation process has started. not related to your problem but worth to mention
then comes validateUser($username); //sets the session data for this user
Now you are calling the function. Let's take a look into the function.
function validateUser($username)
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
$_SESSION['name'] = $userData['name'];
}
You passed $username as parameter but from where $userData['name'] will come? (For scope, refer to MarcBs solution)
So yuu have lot to figure out.

Categories