Link to home
Start Free TrialLog in
Avatar of Michelle Jackson
Michelle Jackson

asked on

PHP Session Variables are not being set

I have a login page, the session variables appear to be set on the login page (I echoed them all back) but when I get to the next page I get  the undefined index error for all of the session variables.
array(0) { } session started

Notice: Undefined index: USERID in D:\Hosting\11817446\html\xxxN\index.php on line 12

Notice: Undefined index: PASSWORD in D:\Hosting\11817446\html\xxx\index.php on line 13

Notice: Undefined index: FNAME in D:\Hosting\11817446\html\xxx\index.php on line 14.

Here is the code from the login page:
// Create and execute the query to get the user's information from the database
$sql = "SELECT * FROM users WHERE UserID = '$username' AND UserPW = '$password'";

$result = mysql_query($sql);

$user_data = mysql_fetch_array($result);
    $numrows = mysql_num_rows($result);
//echo "line 45" .$sql . "";
//exit();
    if ($numrows == 1)
{
	// This is a successful login.  Populate session variables.
	//$arr = mssql_fetch_array($result, MSSQL_ASSOC);

	$_SESSION["USERID"] = $user_data["UserID"];
	$_SESSION["PASSWORD"] = $user_data["UserPW"];
	$_SESSION["FNAME"] = $user_data["FName"];
	$_SESSION["LNAME"] = $user_data["LName"];
	$_SESSION["TITLE"] = $user_data["JobTitle"];
	//echo "login" .$_SESSION['FNAME']."" ;
	

	header("Location: index.php");
	exit();
}
else
{
	$_SESSION['errorMsg'] = "Username or Password invalid.";
	//header("Location: index.php");
	echo "line 61";
	exit();
}

Open in new window

And here is the portion of code from the receiving page where I tried to view the session variables
<?php 
session_start();
var_dump($_SESSION);
ini_set('display_errors',1);
error_reporting(E_ALL);
echo "session started" ."<br />";

if (isset($_SESSION['USERID'])){
	echo "user is not logged in";}
echo $_SESSION["USERID"];
echo $_SESSION["PASSWORD"];  
echo $_SESSION["FNAME"];  

Open in new window

Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

Make sure you call session_start() before you set the variables. That line should be at the very beginning of any page that sets or interacts with session variables.
Avatar of Michelle Jackson
Michelle Jackson

ASKER

Thanks, yes it is at the beginning of each page.
You can use var_dump($_SESSION) to see the session variables.  That may be easier than writing an echo statement for each element of the session array.

Here is an article that tells how the session works.  You might want to check the way the session cookie is handled.
https://www.experts-exchange.com/articles/11909/PHP-Sessions-Simpler-Than-You-May-Think.html
You may also have a looming problem with MySQL.  PHP has dropped support for the MySQL extension, and no currently supported version of PHP still includes support for MySQL.  Fortunately we have an article on that, too!
https://www.experts-exchange.com/articles/11177/Why-PHP-Removed-Support-for-the-MySQL-API.html
And since it looks like you're working toward a PHP client-authentication design (insert drum roll) we have an article about that, too!
https://www.experts-exchange.com/articles/2391/PHP-Client-Registration-Login-Logout-and-Easy-Access-Control.html
Thanks I've done the var_dump($_SESSION); and posted the results in my initial question, I am getting -  array(0) so I am assuming that the variables are not being passed properly but I cannot find an issue with the login page as they can back properly on that page. Thanks
Oh I see what you meant, I added the var_dump to the login page and the variables are correct but this is the error that I got:

array(5) { ["USERID"]=> string(8) "xxxx" ["PASSWORD"]=> string(8) "xxxx" ["FNAME"]=> string(8) "xxx" ["LNAME"]=> string(7) "xxx" ["TITLE"]=> string(7) "xxx" }
Warning: Unknown: open(D:\Temp\php\session\\sess_75cpmu84curbg5lstfafirfi33, O_RDWR) failed: No such file or directory (2) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (D:\Temp\php\session\) in Unknown on line 0
Who is your hosting company?  Is your browser set up to accept and return cookies?

Install this script and experiment with it a little bit.  I've never seen a properly configured PHP system that did not also run this script correctly.
<?php // demo/session_test.php
/**
 * Demonstrate how PHP sessions work
 *
 * Ref: http://php.net/manual/en/book.session.php
 * Ref: http://php.net/manual/en/function.session-start.php
 * Ref: http://www.experts-exchange.com/articles/11909/PHP-Sessions-Simpler-Than-You-May-Think.html
 */
error_reporting(E_ALL);

// START THE SESSION (DO THIS FIRST, UNCONDITIONALLY, IN EVERY PHP SCRIPT ON EVERY PAGE)
session_start();

// INITIALIZE THE SESSION ARRAY TO SET A DEFAULT VALUE
if (!isset($_SESSION["counter"])) $_SESSION["counter"] = 0;

// SEE IF THE INCREMENT SUBMIT BUTTON WAS CLICKED
if (isset($_POST['bump']))
{
    // ADD ONE TO THE COUNTER
    $_SESSION['counter']++;
}

// SEE IF THE DECREMENT SUBMIT BUTTON WAS CLICKED
if (isset($_POST['dump']))
{
    // TAKE ONE FROM THE COUNTER
    $_SESSION['counter']--;
}

// RECOVER THE CURRENT VALUE FROM THE SESSION ARRAY
$counter = $_SESSION['counter'];


// END OF PROCESSING SCRIPT - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<html>
<head>
<title>Session Test</title>
</head>
<body>
Currently, SESSION["counter"] contains: $counter<br/>
<form method="post">
<input type="submit" value="decrement this counter" name="dump" />
<input type="submit" value="leave my counter alone" name="keep" />
<input type="submit" value="increment this counter" name="bump" />
</form>
</body>
</html>
ENDFORM;

echo $form;

Open in new window

Our hosting company is GoDaddy, I ran your script and received the following errors:

Warning: session_start(): open(D:\Temp\php\session\\sess_75cpmu84curbg5lstfafirfi33, O_RDWR) failed: No such file or directory (2) in D:\Hosting\11817446\html\BCN\test_cookies.php on line 12
Currently, SESSION["counter"] contains: 0
 

Warning: Unknown: open(D:\Temp\php\session\\sess_75cpmu84curbg5lstfafirfi33, O_RDWR) failed: No such file or directory (2) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (D:\Temp\php\session\) in Unknown on line 0
Ahh, now we are getting somewhere!  Here are my session-related settings.  Obviously the session "save path" files must be readable and writable by PHP.  This is an excerpt from phpinfo() output.

User generated image
I notice that your path has a double slash in it.  Not sure if that's the problem, but it looks odd.  I also think this should be raised to GoDaddy tech support.  You can show them this question and the dialog here.  They should fix this on the server that houses your hosting.
                    - This looks odd
                    |
                    V
D:\Temp\php\session\\sess_75cpmu84curbg5lstfafirfi33
         

Open in new window

Thank you so very much!!!
If you are renting a Windows VPS from GoDaddy and have access to the filesystem, try just creating this folder path:

D:\Temp\php\session\

It might not exist, which might explain why you're getting those errors.
Hello,
  So I checked with GoDaddy and all of the settings are correct, I set up a save file path directly in the application (when I created a php.ini file to set it, the file did not work) and it is still not saving the session. Here are the current errors:

Warning: Unknown: open(temp/php/session\sess_1gngnnd3vcbfe296evams6f467, O_RDWR) failed: No such file or directory (2) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (temp/php/session) in Unknown on line

Any suggestions on where to go from here? Thank you!
It looks like your new PHP.ini file changed the temp path for session data. If you create the path I suggested and use the old initial file, what does the error say?
Thanks gr8gonzo, but I do not have access to create a that path so I created the new one and set it to what you see above.
You're on a Windows machine and you specified a path that looks like a Linux path. While you CAN use forward slashes instead of backslashes, you should specify the complete path including the drive letter. You need to specify a full path to an existing folder that the web server can write to.
Yes I realized that a few moments ago and changed the path to :
D:\Hosting\xxxx\html\xxxxxxxxx.com\xxx\temp\php\session
 I am still getting the error but now with the new path. I got the absolute path from the GoDaddy site so I am not sure why it is not working properly.
If GoDaddy is offering commercial hosting, it's a basic tenet of merchantability that the PHP session should work correctly.  I suggest you take this issue back to their tech support and ask to "escalate it."  In my personal experience, GoDaddy tech support was notoriously bad, refusing to even acknowledge that anything was wrong, but after I got the question escalated once or twice, we finally found someone who could recognize the issues and fix them.

Or as alternative to GoDaddy, I am happy with ChiHost.  I have also had good experiences with HostGator and LiquidWeb.  Any of these three would have fixed this for you in an instant!
https://www.chihost.com/
http://www.hostgator.com/
https://www.liquidweb.com/
That doesn't seem like the right path. It seems like that would put your session files into a publicly-accessible space, which would be a bad thing for security. Honestly, you might have to go through the pains of contacting GoDaddy support for help and proper setup here. Session files should go into a temp folder that is NOT within your public document root folder.

I agree with Ray that GoDaddy's support is notoriously bad. I personally use them for domain registration and DNS, and they're great for that, but their hosting and hosting support is a bit of a joke. It seems to be a rite of passage for many people to sign up with GoDaddy hosting and experience the problems and then switch over to something else. Whenever I come across a random post from someone complaining about a configuration problem (often times it's mail-related), more often than not, it's someone on GoDaddy hosting.

The catch is that you've already spent money on GoDaddy, so it's sort of a pain and a hassle to switch. So even if you don't want to switch now, you might want to consider researching alternatives for the future and just open a tech support ticket with them for now (so you can get the whole experience).

I've also used LiquidWeb and HostGator. If you're interested in more of a low-cost dedicated server instead of shared, I'd recommend Atlantic.Net. Some of the entry-level servers are on-par with the performance of shared services but with better security, although they require a little more technical knowledge to ensure they are being set up correctly.
Thank you of all of your advice. I am trying a workaround and it's almost there. I am validating the login first and then just passing the username in the URL however; my receiving page is not getting the username, I see it in the string but when I try to set the variable it remains blank.
Here is what I am sending:
 header("location: index.php?user=<?php echo $myusername; ?>");

Open in new window

and here is how I am trying to retrieve it:
 $user_id                =  $_GET['user'];

Open in new window

The string that is sent is:
http://xxxxxx.com/xxx/index.php?user=%3C?php%20echo%20mjackson;%20?%3E

I think it's probably something simple that I am missing but I just need another set of eyes. Thanks in advance!
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you Ray, that worked but I will definitely take the safer approach...thank you all for your input!!!
Glad you've got it pointed in the right direction, and thanks for the points, Michelle.  Going forward, it's always appropriate to share the points among the contributors.  This was a complicated issue that required some diverse exploration, and for those endeavors, it's fine with me (and everyone else) to make a split of the rewards.  Cheers, ~Ray