Jump to content

Undefined Index in $_SESSION


ShadowMage

Recommended Posts

I have the following code in a test document:

require('ValidateSession.php');

// echo "<pre>".print_r($_SESSION, true)."</pre>";
echo "User: ".$_SESSION['User'];

As written above (with the print_r line commented out and attempting to access the 'User' index) I get the following error:

Quote

PHP Notice:  Undefined index: User in C:\inetpub\major\test.php on line 24

If I swap the two echo lines (so the print_r is no longer commented and the other line is) it redirects to the login page as expected.  This is what the ValidateSession.php is supposed to do.  It checks whether there is a current/valid session and if not, redirects to a login page.  I can post this code if it will help.

A little more context on some things.  We're in the process of migrating to a new web server going from 32-bit PHP 5.5.15 to 64-bit PHP 7.4.3.  I went through the INI files and got them as close as possible.  Is there some setting or behavior that makes the above function differently in the new version?  The above works as intended on our current server.

Any help you can offer would be much appreciated.  Thanks in advance.

Link to comment
Share on other sites

You should check that the index exists before trying to use it:

if(isset($_SESSION['User'])) {
  echo "User: ".$_SESSION['User'];
} else {
  echo "No user";
}

If your previous server was not showing a warning at this line then you probably were suppressing warnings.

Link to comment
Share on other sites

Ok, so I tried using isset to check the session variable, but that seems to have just bypassed the whole logon and redirected me to a random homepage (not quite) with even more session variable errors.  Just to clarify, this is on a company intranet where users log in and are directed to a department-related homepage.

I'm not sure if I can accurately explain everything, but I'll try, so here goes. 

This is what is supposed to happen (pseudo-code, obviously):

ValidateSession {
	check for valid session
	if (!valid) redirect to logon
}

Get user dept based on user ID from session
Redirect to appropriate homepage

This code is all in the _index.php file (where the user lands after typing the intranet address), except for the ValidateSession which is in an includes file as seen before.  This is the behavior that is happening on our current web server.  Copying that code over, exactly, to our new server results in the error mentioned previously.  It doesn't seem to allow any other output except the error message.  When I try to access an undefined index on the current server, I get the undefined index notice, but it's in the middle of the rest of the page output.

That said, I did try to use isset to check the session variable first and that resulted in the following behavior:

require('ValidateSessin.php');  //This doesn't seem to actually execute but I included it to show that it is still in my actual code

isset($_SESSION['User'])
	$User = $_SESSION['User']
else
	$User = '' //this is the block being executed because it seems to entirely skip the ValidateSession code above

Execute query to pull user dept; finds random user in DB with blank ID (ID is not the PK of DB)
Redirect to random user's "homepage"

This results in a good many undefined index notices because the homepages use the session variable to determine specific users that can see specific tools and links so every time it tries to check a session variable it throws a notice.  As I mentioned, it seems to just entirely skip the ValidateSession code whenever I try to actually access the session variables.  If I just want to print out the session, it works just fine.

Edited by ShadowMage
edited code for clarity
Link to comment
Share on other sites

I debated just editing my last post and changing it completely, but I decided to leave it in case it's more useful than it appears to me.

Anyway, here's a more accurate illustration of what's going on.  This is the code for ValidateSession.php:

<?php
session_start();

// must have a valid cookie
if ( isset($_COOKIE['MajorEpicor10Login']) ) {
	// split the cookie data into an array
	parse_str($_COOKIE['MajorEpicor10Login'], $tmparr);
	if ( !(isset($_SESSION['User']) and ($_SESSION['User'] == $tmparr['User'])) ) {
		$_SESSION['User'] = $tmparr['User'];
		$_SESSION['FirstName'] = $tmparr['FirstName'];
		$_SESSION['LastName'] = $tmparr['LastName'];
		$_SESSION['Staff'] = $tmparr['Staff'];
		$_SESSION['OutsideSales'] = $tmparr['OutsideSales'];
		$_SESSION['GroupList'] = $tmparr['GroupList'];
		$_SESSION['DepartmentID'] = $tmparr['DepartmentID'];
	
		setrawcookie("MajorEpicor10Login", $_COOKIE['MajorEpicor10Login'], time()+60*60*24*30, '/');
	}
} else {
	header('Location: /Logon/Logon.php?From=Home');
}
//die();
?>

Now, using my test code from my original post:

require('ValidateSession.php');
echo "User: ".$_SESSION['User'];

produces the error.  If I un-comment the die() command in ValidateSession, it will redirect successfully to the logon.php page.  Same behavior in my actual code which looks something like this (there is some pseudo-code):

<?php
require('ValidateSession.php');
$User = $_SESSION['User'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	
<html>
<head>
<title>Major Web Portal</title>
</head>
<body>
<form name="MajorWebPortal">

<?php
/**SQL query to pull user data such as DepartmentID**/

if ($RecordExists) {
	switch ($DepartmentID) {
		/**Redirect to dept homepage using header()**/
	}
} else {
	header('Location: ./Logon/Logon.php?From=SetCookie');
}
?>
</form>
</body>
</html>

Now if I put this bit:

$User = '';
if (isset($_SESSION['User'])) {
	$User = $_SESSION['User'];
}

into each file in place of direct access to the session variable, the test code will successfully redirect back to the logon page while my actual code proceeds on down through the rest of the code, pulling in a "random" user with a blank ID and redirecting to that user's homepage (where I then get a bunch more undefined index errors).  I presume the header() call in ValidateSession is being overwritten by the header() calls in the index page, but why is the code even going that far instead of just executing the first header() call like it does on our current server?

Edited by ShadowMage
Link to comment
Share on other sites

You should call exit or die any time you're redirecting a user to prevent the code from executing any of the instructions that are further down. Nothing about the header() function tells the code to stop executing.

header('Location: /Logon/Logon.php?From=Home');
exit;

 

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

That's what I ended up doing.  If this is a standard coding practice, I'm not sure why it worked before (I didn't write any of this stuff, but it was working so I never gave any thought to good practice).  Thanks for the help!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...