Object & session properties are not returned from the class function into the initiating script, even though the classes and objects initiate. I can see their properties with var_dump() from within the class function but they are not returned outside the class function.
I have a globally included file global.inc.php which gets called on every page which does a bunch of things. On user form Login, the include calls a custom class ('UserTools.class.php') using:
$userTools = new UserTools();
This class does 3 things:
public function login($username, $password) {
$result = mysql_query("SELECT * FROM users WHERE username = '$username'");
$row = mysql_fetch_assoc($result);
$_SESSION["login_time"] = time();
$_SESSION["logged_in"] = true;
$_SESSION["passwordHash"] = $passwordHash;
$_SESSION["user"] = serialize(new User($row));
If I var_dump($_SESSION['user']) from "within" the class, I can see the serialized string representation of the User object:
var_dump($_SESSION['user']):
array (size=4)
'SESS_PARENT' => boolean true
'SESS_CHILD' => boolean true
'timezone' => int 300
'user' => string 'O:4:"User":13: {s:2:"id";s:1:"1";s:8:"username";s:5:"peter";s:14:"hashedPassword";s:60:"$2y$11.....(length=6160)
THE PROBLEM
But when the class function returns to the calling global.in.php script, the complete $_SESSION variable is:
array (size=0) . empty
Q1. What am I doing wrong here?
Q2. What has changed since php 5.3 to have this effect?
The culprit turned out to be the $_SESSION superglobal and a complex set of includes.
session_start();
was not at the start of the include file, only some way down after some ini_set commands setting up various parameters for the $_SESSION superglobal.
Header redirects were not saving session data.
This is because, any changes to $_SESSION varibles are made when a script ends. A header redirect with an exit()
statement is essentially interrupting a script’s execution - so the session needs to be written back to disk, database or Redis 'before' the redirect and exit() commands are called.