Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Storing objects in PHP session
In PHP, you can store objects in sessions using the serialize() and unserialize() functions. The serialize() function converts an object into a storable string representation, while unserialize() recreates the object from that string.
Storing Objects in Session
To store an object in a session, first serialize it and then assign it to the $_SESSION superglobal ?
<?php session_start(); $object = new sample_object(); $_SESSION['sample'] = serialize($object); ?>
The session is started using session_start(), a new object is created, then serialized and stored in the session variable.
Retrieving Objects from Session
To retrieve the stored object, use the unserialize() function ?
<?php session_start(); $object = unserialize($_SESSION['sample']); ?>
Example − Serialize Array
Here's how serialization works with an array ?
<?php
$data = serialize(array("abc", "defgh", "ijkxyz"));
echo $data;
?>
a:3:{i:0;s:3:"abc";i:1;s:5:"defgh";i:2;s:6:"ijkxyz";}
Example − Serialize and Unserialize
This example demonstrates both serialization and unserialization ?
<?php
$data = serialize(array("abc", "defgh", "ijkxuz"));
echo $data . "<br>";
$test = unserialize($data);
var_dump($test);
?>
a:3:{i:0;s:3:"abc";i:1;s:5:"defgh";i:2;s:6:"ijkxuz";}
array(3) { [0]=> string(3) "abc" [1]=> string(5) "defgh" [2]=> string(6) "ijkxuz" }
Conclusion
Using serialize() and unserialize() allows you to store complex objects in PHP sessions effectively. Always ensure the object's class definition is available when unserializing to avoid errors.
