Store Object in PHP Session
Use serialize()
in PHP before store your object, and call unserialize()
when retrieve your object from session.
store object
session_start();
$object = new sample_object();
$_SESSION['sample'] = serialize($object);
retrieve object
session_start();
$object = unserialize($_SESSION['sample']);
PHP: Storing 'objects' inside the $_SESSION
I know this topic is old, but this issue keeps coming up and has not been addressed to my satisfaction:
Whether you save objects in $_SESSION, or reconstruct them whole cloth based on data stashed in hidden form fields, or re-query them from the DB each time, you are using state. HTTP is stateless (more or less; but see GET vs. PUT) but almost everything anybody cares to do with a web app requires state to be maintained somewhere. Acting as if pushing the state into nooks and crannies amounts to some kind of theoretical win is just wrong. State is state. If you use state, you lose the various technical advantages gained by being stateless. This is not something to lose sleep over unless you know in advance that you ought to be losing sleep over it.
I am especially flummoxed by the blessing received by the "double whammy" arguments put forth by Hank Gay. Is the OP building a distributed and load-balanced e-commerce system? My guess is no; and I will further posit that serializing his $User class, or whatever, will not cripple his server beyond repair. My advice: use techniques that are sensible to your application. Objects in $_SESSION are fine, subject to common sense precautions. If your app suddenly turns into something rivaling Amazon in traffic served, you will need to re-adapt. That's life.
How can I store objects in a session in PHP?
PHP's native $_SESSION
sessions transparently serialize and unserialize objects that support PHP's serialization protocol or the Serializable
interface. You do not need to explicitly serialize them.
PHP cannot serialize resources
because these are handles to some stateful resource outside PHP's control. This is why you cannot serialize PDO
or PDOStatement
objects.
By default an object is serialized by saving all property names and values and unserialized by creating an object with the same class (without invoking the constructor) and directly setting the serialized properties. You can customize serialization behavior for your objects using the __sleep
and __wakeup
magic methods or by implementing the Serializable
interface. But not both! If you use implements Serializable
, __sleep
and __wakeup
are ignored.
One important note: when using object serialization, you must have the class definition loaded before you unserialize (or have an autoloader that can load it) and it must match the class definition of the object that was serialized. Class definitions are not stored in the serialized data.
For example suppose you have the following:
class Test {
public $version = 1;
protected $abc;
public function setAbc($abc) {
$this->abc = $abc;
}
}
$t = new Test();
$t->setAbc(123);
$_SESSION['mytest'] = $t;
Now imagine you change Test
one day to be like this instead:
class Test {
public $version = 2;
private $def;
public function setDef ($def) {
$this->def = $def;
}
}
Now suppose you load into your new code an object serialized when Test
was at version 1:
$t = $_SESSION['mytest']; // this was stored yesterday, when Test was version 1
var_dump($t)
You will get this:
object(Test)#1 (3) {
["version"]=>
int(1)
["def":"Test":private]=>
NULL
["abc":protected]=>
int(123)
}
Furthermore, you can't use old methods:
if ($t->version == 1) { // Check for class version
$t->setAbc(345); // "Fatal error: Call to undefined method Test::setAbc()"
}
Storing objects inside a session
Before unserializing you need to do the same thing you would before creating an instance of the object normally:
$profile = new Profile("u", "p");
That is, make sure you have included all the files that define that class. That is what the error message is trying to tell you:
Please ensure that the class definition "Profile" of the object you are trying to operate on was loaded before unserialize() gets called
So do something like this:
<?php
require_once '/path/to/Profile.class.php';
session_start();
$profile = unserialize($_SESSION['profile']);
Can I store a class instance in a $_SESSION space?
You must first serialize the object in to a string:
$_SESSION['user'] = serialize($user);
and:
$user = unserialize($_SESSION['user']);
Just make sure that the class is first defined before unserializing the object.
how to save many objects in a $session array variable
This is working for me locally.
Define your items session variable as an array, then push them into the variable using array_push
class product {
public $prodId;
public $prodName;
public $prodPrice;
public function __construct($prodId, $prodName, $prodPrice) {
$this->prodId = $prodId;
$this->prodName = $prodName;
$this->prodPrice = $prodPrice;
}
public function get_prodId() {
return $this->prodId;
}
public function get_prodName() {
return $this->prodName;
}
public function get_prodPrice() {
return $this->prodPrice;
}
}
Then use it like so:
$product = new product(1, "test", 23);
$product2 = new product(2, "test2", 43);
$_SESSION['items'] = array();
array_push($_SESSION['items'], $product, $product2);
echo '<pre>';
print_r($_SESSION['items']);
echo '</pre>';
This is the output of print_r()
Array
(
[0] => product Object
(
[prodId] => 1
[prodName] => test
[prodPrice] => 23
)
[1] => product Object
(
[prodId] => 2
[prodName] => test2
[prodPrice] => 43
)
)
Saving object to a session - How do I fetch my object from the session as it was before?
You should use the function serialize()
to returns a string containing a byte-stream representation of value, In reverse you can use unserialize()
. Because you can not store object in PHP SESSION
.
The code should be,
session_start();
$a = your_object;
$b = serialize($a);
$_SESSION["serialized_data"] = $b;
# To store in Session
$unserialized_data = unserialize($_SESSION["serialized_data"]);
# To get from Session as Object
Related Topics
How to Remove Both .PHP and .Html Extensions from Url Using Nginx
How to Detect Duplicate Values in PHP Array
PHP Error: Cannot Modify Header Information - Headers Already Sent
The MySQLi Extension Is Missing. Please Check Your PHP Configuration
The Character Encoding of the HTML Document Was Not Declared
How to Combine Two Arrays Together
PHP: Convert Unicode Codepoint to Utf-8
How to Fix Trying to Access Array Offset on Value of Type Null Error
Sqlstate[Hy000] [2002] Connection Refused Within Laravel Homestead
How to Get Random Value Out of an Array
What Type of Hash Does Wordpress Use
How to Get the Value of an Attribute from Xml File in PHP
How to Check File Types of Uploaded Files in PHP
Including a Remote File in PHP
How to Check Whether the User Uploaded a File in PHP
How to Test If a MySQL Query Was Successful in Modifying Database Table Data