In PHP, the basic purpose of serialization and deserialization is to convert objects or arrays into strings for easier data storage or network transmission, and vice versa. Serialization converts data into a string, while deserialization converts the string back into its original data type, such as an object or array.
PHP provides the serialize() function to convert objects or arrays into a string. For example:
$data = [
'name' => 'John Doe',
'age' => 30
];
$serialized_data = serialize($data);
At this point, the $serialized_data variable will hold a string containing the serialized data.
To restore a serialized string back into its original object or array form, PHP provides the unserialize() function. For example:
$unserialized_data = unserialize($serialized_data);
var_dump($unserialized_data);
This will output the original data structure:
array(2) {
'name' => string(8) "John Doe",
'age' => int(30)
}
In practical applications, serialization and deserialization are often used to store session data, preventing data loss when the user closes the browser or accesses the website from different devices. You can use serialize() to store session data in the database:
$data = [
'user_id' => 123,
'cart_items' => ['item1', 'item2']
];
$serialized_data = serialize($data);
$_SESSION['saved_data'] = $serialized_data;
Later, you can load the session data using unserialize() when needed:
$serialized_data = $_SESSION['saved_data'];
$data = unserialize($serialized_data);
You can access the restored data at any time:
echo $data['user_id']; // Outputs: 123
echo $data['cart_items'][0]; // Outputs: item1
With serialization and deserialization, PHP offers powerful features for data storage and transmission, especially for saving and recovering session data. Mastering these techniques will help you handle session and data storage problems more efficiently on your website.