serialize() / unserialize()
| Since: | PHP 4(2000) |
|---|
Functions that convert PHP values into a byte string for storage or transfer, and restore them back to their original values. Commonly used for saving session data and caching. The serialized string looks something like a:2:{s:4:"name";s:11:"Yagami Iori";}.
Syntax
serialize($value); // Restores a serialized string back to its original PHP value. unserialize($data, $options);
Function List
| Function | Description |
|---|---|
| serialize($value) | Converts a PHP value into a byte string. Supports nearly all types including arrays, objects, integers, and strings, but cannot serialize resource types or closures. |
| unserialize($data, $options) | Restores a serialized string back to its original PHP value. The allowed_classes option in the second argument lets you restrict which classes are allowed to be restored. |
Sample Code
sample_serialize.php
<?php
// Serialize an array.
$data = ['name' => 'Yagami Iori', 'age' => 20, 'skills' => ['PHP', 'JavaScript', 'Arashi no Saxophone 2']];
$serialized = serialize($data);
echo $serialized . "\n"; // Outputs the serialized string.
// Restore the serialized string.
$restored = unserialize($serialized);
echo $restored['name'] . "\n"; // Outputs "Yagami Iori".
print_r($restored['skills']); // Restores the original array.
// Check the serialized output for various types.
echo serialize(42) . "\n"; // Outputs "i:42;".
echo serialize(3.14) . "\n"; // Outputs "d:3.14;".
echo serialize("PHP") . "\n"; // Outputs 's:3:"PHP";'.
echo serialize(true) . "\n"; // Outputs "b:1;".
echo serialize(null) . "\n"; // Outputs "N;".
// Serialize an object.
class UserData {
public function __construct(
public string $name,
public string $email
) {}
}
$user = new UserData("Kusanagi Kyo", "kusanagi_kyo@wp-p.info");
$serialized_user = serialize($user);
echo $serialized_user . "\n";
// Safe unserialize: restrict classes using allowed_classes.
$safe_data = unserialize($serialized_user, [
'allowed_classes' => ['UserData'] // Only allow the UserData class to be restored.
]);
echo $safe_data->name . "\n"; // Outputs "Kusanagi Kyo".
// Setting allowed_classes to false rejects all classes.
$no_objects = unserialize($serialized_user, [
'allowed_classes' => false // Objects become __PHP_Incomplete_Class instances.
]);
// Example of saving data to a file.
$settings = [
'theme' => 'dark',
'lang' => 'ja',
'notifications' => true
];
file_put_contents('/tmp/settings.dat', serialize($settings));
$loaded = unserialize(file_get_contents('/tmp/settings.dat'), [
'allowed_classes' => false
]);
echo $loaded['theme'] . "\n"; // Outputs "dark".
// Comparison with JSON. Use JSON when exchanging data with external systems.
$data = ['id' => 1, 'title' => 'PHP Basics'];
echo serialize($data) . "\n"; // PHP-specific format
echo json_encode($data) . "\n"; // Format readable by other languages
Running the code produces the following output:
php sample_serialize.php
a:3:{s:4:"name";s:11:"Yagami Iori";s:3:"age";i:20;s:6:"skills";a:3:{i:0;s:3:"PHP";i:1;s:10:"JavaScript";i:2;s:21:"Arashi no Saxophone 2";}}
Yagami Iori
Array
(
[0] => PHP
[1] => JavaScript
[2] => Arashi no Saxophone 2
)
i:42;
d:3.14;
s:3:"PHP";
b:1;
N;
O:8:"UserData":2:{s:4:"name";s:12:"Kusanagi Kyo";s:5:"email";s:22:"kusanagi_kyo@wp-p.info";}
Kusanagi Kyo
dark
a:2:{s:2:"id";i:1;s:5:"title";s:9:"PHP Basics";}
{"id":1,"title":"PHP Basics"}
Notes
serialize() converts a PHP value into a byte string, which is useful for storing complex data structures in files or databases. PHP's session mechanism also uses serialize() and unserialize() internally to save and restore session data.
Always specify the allowed_classes option in the second argument when using unserialize(). Unserializing untrusted data without allowed_classes can restore malicious objects, potentially leading to remote code execution vulnerabilities. When unserializing external input, set allowed_classes => false to prevent object restoration entirely.
When exchanging data with external systems, JSON is preferable as it is not PHP-specific. Use json_encode() / json_decode() for JSON. For debug output, see 'var_dump()'.
If you find any errors or copyright issues, please contact us.