
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
Storing objects in PHP session
The serialize() function in PHP can be used before storing the object, and the unserialize() function can be called when the object needs to be retrieved from the session.
The function converts a storable representation of a specific value into a sequence of bits. This is done so that the data can be stored in a file, a memory buffer or can be transferred over a network.
Using the serialize function to store the object −
session_start(); $object = new sample_object(); $_SESSION['sample'] = serialize($object);
The session is started by using the ‘session_start’ function and a new object is created. The object created is serialized using the ‘serialize’ function and assigned to the _SESSION variable.
Example
<?php $data = serialize(array("abc", "defgh", "ijkxyz")); echo $data; ?>
Output
This will produce the following output −
a:3:{i:0;s:3:"abc";i:1;s:5:"defgh";i:2;s:6:"ijkxyz";}
Using the unserialize function to retrieve the object −
session_start(); $object = unserialize($_SESSION['sample']);
As usual, the session is begun using the ‘session_start’ function and the object that was created previously, that was serialized by assigning it to the _SESSION variable is unserialized using the ‘unserialize’ function −
Example
<?php $data = serialize(array("abc", "defgh", "ijkxuz")); echo $data . "<br>"; $test = unserialize($data); var_dump($test); ?>
Output
This will produce the following output −
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" }
- Related Articles
- Reading and storing a list as an array PHP
- PHP Objects.
- PHP Comparing Objects
- How to Check if PHP session has already started?
- Creating anonymous objects in PHP
- PHP Objects and references
- PHP Generators vs Iterator objects
- Storing Credentials in Local Storage
- Storing money amounts in MySQL?
- Storing static attribute values in ABAP
- PHP Call methods of objects in array using array_map?
- Extract a property from an array of objects in PHP
- How do you pass objects by reference in PHP 5?
- What is session attribute in JSP?
- Working with tmux session
