Why isn't my variable being set with SESSION variable? - php

I am thinking this is a syntax issue but I have tried it a few different ways. PHP 5.4.16 running on IIS 6 (these are not my choices).
I cannot get $usr to be set to $_SESSION['uid']. I ran a dump right after setting it and I see the uid info for the session data but NULL for $usr. Syntax wrong? What do you think is going on?
function User_CustomValidate(&$usr, &$pwd) {
session_start(); // Initialize Session data
ob_start(); // Turn on output buffering
$appKey = "pwssssssssssssss";
$safeurl = 'https://safe.ssssss.com/login/sso/SSOService?app=playbooks';
// first call back after safe login - POST is set
if ($_POST && isset($_POST['digest']))
{
$digest = $_POST["digest"];
// set the session variables ...
$_SESSION['usernames'] = $_POST["firstname"]." ".$_POST["lastname"];
$_SESSION['firstname'] = $_POST["firstname"];
$_SESSION['lastname'] = $_POST["lastname"];
$_SESSION['email'] = $_POST["email"];
$_SESSION['uid'] = $_POST["uid"];
// Needed for key
$uid = $_POST["uid"];
$time = $_POST["time"];
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
$mykey = "".$uid.$time.$appKey;
$mydigest = md5($mykey);
}
// session is not initialized as we never got the post above to set session vars
// call now the safe login to get the post to set the session vars ...
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
header("Location: ".$safeurl);
}
$usr = $_SESSION['uid'];
var_dump($usr, $_SESSION['uid']);
$this->setCurrentUserName($usr);
return TRUE;
}
So var_dump shows $usr = NULL and $_SESSION['uid'] with proper employee ID passed by SSO.

Have you verified that your POST data is correct? I think the issue may be, without seeing the surrounding code, that the code inside your if statements are not being executed. You need to confirm that your POST variable "digest" is set. Or for testing if before that if statement you set $_POST['digest'] and $_POST['uid'] then you will find i think that the var_dump will not be null.
function User_CustomValidate($usr, $pwd) {
session_start(); // Initialize Session data
ob_start(); // Turn on output buffering
$appKey = "pwssssssssssssss";
$safeurl = 'https://safe.ssssss.com/login/sso/SSOService?app=playbooks';
// first call back after safe login - POST is set
$_POST['digest'] = 'test';
$_POST['uid'] = 1234;
if ($_POST && isset($_POST['digest'])) {
$digest = $_POST["digest"];
// set the session variables ...
$_SESSION['usernames'] = $_POST["firstname"]." ".$_POST["lastname"];
$_SESSION['firstname'] = $_POST["firstname"];
$_SESSION['lastname'] = $_POST["lastname"];
$_SESSION['email'] = $_POST["email"];
$_SESSION['uid'] = $_POST["uid"];
// Needed for key
$uid = $_POST["uid"];
$time = $_POST["time"];
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
$mykey = "".$uid.$time.$appKey;
$mydigest = md5($mykey);
}
// session is not initialized as we never got the post above to set session vars
// call now the safe login to get the post to set the session vars ...
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
header("Location: ".$safeurl);
}
$usr = $_SESSION['uid'];
var_dump($usr, $_SESSION['uid']);
$this->setCurrentUserName($usr);
return TRUE;
}

Related

Why is my session variable not passing correctly?

function User_CustomValidate(&$usr) {
$appKey = "xxxxx";
$safeurl = 'https://safe.xxxx.com/login/sso/SSOService?app=playbooks';
// first call back after safe login - POST is set
if ($_POST && isset($_POST['digest']))
{
$digest = $_POST["digest"];
// set the session variables ...
$_SESSION['username'] = $_POST["firstname"]." ".$_POST["lastname"];
$_SESSION['firstname'] = $_POST["firstname"];
$_SESSION['lastname'] = $_POST["lastname"];
$_SESSION['email'] = $_POST["email"];
$_SESSION['uid'] = $_POST["uid"];
// Needed for key
$uid = $_POST["uid"];
$time = $_POST["time"];
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
$mykey = "".$uid.$time.$appKey;
$mydigest = md5($mykey);
}
// session is not initialized as we never got the post above to set session vars
// call now the safe login to get the post to set the session vars ...
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
header("Location: ".$safeurl);
}
$usr = $_SESSION['uid'];
$this->setCurrentUserName($usr);
return TRUE;
}
I am creating a SSO function that is supposed to carry over the SSO digest data to my applications. I am having an issue with a variable that I cannot figure out. All of my SESSION variables are working and I can clearly see their results on all of my pages. So when I echo $_SESSION['uid'] I can see whatever uid that is passed from our SSO. But I am getting nothing from $usr. I have the statement $usr = $_SESSION['uid'] and it returns nothing. However when I set $usr to '888888' it returns that static uid and everything works. How can I get the session uid passed right?

making session variable active on dynamically created subdomains

I was working on a web project which allows users to create their own sub domains dynamically.
Before creating a subdomain they should be logged in to the website.
And now was wondering how to set session variable of a user active even on the subdomains which he visits.
Tried with lot of functions like
session_set_cookie_params(0, '/', '.example.com');
**ini_set('session.cookie_domain', '.example.com' );**
but all in no wain. No function works .
So please do suggest me how to handle this.
here is my code which starts the session as soon as the user log's in:
checkusrlog.php
<?php
//for session to be active on subdomain
session_set_cookie_params(0, '/', '.xyz.com');
session_start(); // Start Session First Thing
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once "connectiontomysql.php"; // Connect to the database
$dyn_www = $_SERVER['HTTP_HOST'];
//------ CHECK IF THE USER IS LOGGED IN OR NOT AND GIVE APPROPRIATE OUTPUT -------
$logOptions = ''; // Initialize the logOptions variable that gets printed to the page
$newMessage = '';
// If the session variable and cookie variable are not set this code runs
if (!isset($_SESSION['idx'])) {
if (!isset($_COOKIE['idCookie'])) {
$logOptions = 'Register Account
|
Log In';
}
}
// If session ID is set for logged in user without cookies remember me feature set
if (isset($_SESSION['idx'])) {
$decryptedID = base64_decode($_SESSION['idx']);
$id_array = explode("p3h9xfn8sq03hs2234", $decryptedID);
$logOptions_id = $id_array[1];
} else if (isset($_COOKIE['idCookie'])) {// If id cookie is set, but no session ID is set yet, we set it below and update stuff
$decryptedID = base64_decode($_COOKIE['idCookie']);
$id_array = explode("nm2c0c4y3dn3727553", $decryptedID);
$userID = $id_array[1];
$userPass = $_COOKIE['passCookie'];
// Get their user first name to set into session var
$sql_uname = mysql_query("SELECT username, email FROM siteMembers WHERE id='$userID' AND password='$userPass' LIMIT 1");
$numRows = mysql_num_rows($sql_uname);
if ($numRows == 0) {
// Kill their cookies and send them back to homepage if they have cookie set but are not a member any longer
setcookie("idCookie", '', time()-42000, '/');
setcookie("passCookie", '', time()-42000, '/');
header("location: index.php"); // << makes the script send them to any page we set
exit();
}
while($row = mysql_fetch_array($sql_uname)){
$username = $row["username"];
$useremail = $row["email"];
}
$_SESSION['id'] = $userID; // now add the value we need to the session variable
$_SESSION['idx'] = base64_encode("g4p3h9xfn8sq03hs2234$userID");
$_SESSION['username'] = $username;
$_SESSION['useremail'] = $useremail;
$_SESSION['userpass'] = $userPass;
$logOptions_id = $userID;
?>
Note: all subdomains are managed with only single piece of code where the data which belogs to that particular subdomain is dump from database dynamically based on the subdomain.
In between am working on a shared hosting service and using *.streamicon.com as Root domain. Using *.streamicon.com as my root domain as it allows me to create 'n' number of subdomains dynamically.

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.

PHP to Python Server Pages, Sessions and EXEC

I'm trying to convert this PHP to psp(python server pages). I'm at a loss with the php exec function and isset for the session variables.
session_start();
if(isset($_POST["var"])){
//set session username
$username = (string)$_POST["var"];
$username = trim($username);
$_SESSION['username'] = $username; //store $username
}
if(isset($_SESSION['username'])){
$username = $_SESSION['username']; //store session[username] as $username
$cmd = '/var/www/cgi-bin/resolveID.py ' . escapeshellcmd($username);
$fullname = exec($cmd);
$_SESSION['fullname'] = $fullname;
}
else{
echo 'Your session has expired, please click here';
exit;
}
This is what i have
<%
import cgitb, session
cgitb.enable()
user_session = Session.Session()
#post info
if form.getvalue('var'):
varUsername = form.getvalue('var')
user_session['username'] = varUsername
#session set stuff
try:
if user_session['username']:
#is set
varUsername = user_session['username']
varCMD = '/var/www/cgi-bin/resolveID.py ' + varUsername
varFullname = subprocess.check_output(varCMD)
user_session['fullname'] = varFullname
except:
#not set
req.write('Your session has expired, please click here')
%>
I think subprocess.check_output() is the function you are looking for:
fullname = subprocess.check_output(['/var/www/cgi-bin/resolveID.py', username])
Instead of isset($array['key']) you use 'key' in array in python.

Local vars interfere with $_SESSION vars?

The output of the following code on a random page is :
print $_SESSION['uid']; // logged in user
// Get Data .
$uid = $_GET['ID']; // part of random page processing
print $_SESSION['uid'];
is :
1
2
My logged in User ID is changing ! :#
The code for the login (authenticate) page is something like this :
// Authenticate
$query = "SELECT * FROM User WHERE Email = '".$Email."' AND Password = '".$Password."'";
$result = mysql_query($query);
// Authenticated?
if(mysql_num_rows($result)) {
// Yes
// Set session Vars
$uid = mysql_result($result,0,ID);
$Access = mysql_result($result,0,Access);
session_destroy();
session_start();
$_SESSION['loggedIN'] = 1;
$_SESSION['Access'] = $Access;
$_SESSION['uid'] = $uid;
// Print a successful login and redirect
What you're seeing is a side-effect of register_globals. Basically:
$uid
and
$_SESSION['uid']
reference the same variable so when you do:
$uid = $_GET['ID'];
it's the equivalent of:
$SESSION['uid'] = $_GET['ID'];
My advice? Turn off register globals. It's deprecated in PHP 5.3 and will be removed in PHP 6. To turn it off, edit your php.ini file and change to this directive:
register_globals = Off
then restart Apache (or whatever your Web server is).
That's weird... Are you sure you're not doing $_SESSION['uid']++ anywhere?
Also, do you have register_globals on?
register_globals should be off by default.
Is there some call to session_register anywhere?

Categories