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

 Live Demo

<?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

 Live Demo

<?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" }

Updated on: 09-Apr-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements