bkap
bkap

Reputation: 13

Object Session not being passed

On File A.php I have a while Loop that pulls data from a database and connects to class.php to create objects for each dataset. That part works fine.
Within that Loop I try to save each object to a SESSION defined by its id value after New Object has been created

File A.php:

$_SESSION[$pObject->id] = $pObject;

if (isset($_SESSION[$pObject->id]))

{

echo "SESSION $pObject->id is set"; 

}

I have confirmed that it IS being created.

NOW, I have a form that sends an Objects id value via a GET to File B.php, I have confirmation that the value is received.

File B.php:

require_once 'class.php';

session_start();

$id = $_GET['id'];

echo $id;

//Now $id is in my new file, so I try to call my SESSION

if(isset($_SESSION[$id]))

{

echo "SESSION $id is set";

$pObjectCurrrent = $_SESSION[$id];

}

else{

echo "SESSION $id is Not set";

}

The issue is, that despite $id in File B.php being equal to the value of $pObject->id in File A.php the SESSION[$id] in File B.php is NOT set and has no value. Instead I receive an undefined variable error. Any ideas would be greatly appreciated.

Upvotes: 1

Views: 141

Answers (1)

Gabriel Harper
Gabriel Harper

Reputation: 444

You can't use an integer as your session variable name.

You could set the session var like this:

$_SESSION['obj' . $pObject->id] = $pObject;

Then retrieve it from B.php like this:

echo $_SESSION['obj' . $id];

Essentially that concatenates the ID with a string so the variable name would be "obj5", "obj2", etc.

Also - if you're passing a lot of data in session objects, I'd recommend researching serializing and alternatives like storing session data to DB.

Upvotes: 1

Related Questions