The unserialize Function
The unserialize function takes a serialized string
and returns the corresponding PHP value. Its first parameter
is the string, and the second optional parameter is
an array of options to control the deserialization process.
Syntax
unserialize(string $data, array $options = []): mixed
Example
Convert a serialized string back to an array:
<?php
$serialized = 'a:3:{i:0;s:1:"a";i:1;s:1:"b";i:2;s:1:"c";}';
$res = unserialize($serialized);
print_r($res);
?>
Code execution result:
['a', 'b', 'c']
Example
Object deserialization:
<?php
class Test {
public $prop = 123;
}
$obj = new Test();
$serialized = serialize($obj);
$res = unserialize($serialized);
echo $res->prop;
?>
Code execution result:
123
Example
Using the 'allowed_classes' option:
<?php
$serialized = 'O:4:"Test":1:{s:4:"prop";i:123;}';
$res = unserialize($serialized, ['allowed_classes' => false]);
var_dump($res);
?>
Code execution result:
object(__PHP_Incomplete_Class)#1 (2) {
["__PHP_Incomplete_Class_Name"]=>
string(4) "Test"
["prop"]=>
int(123)
}
See Also
-
the
serializefunction,
which converts a value to a serialized string -
the
json_encodefunction,
which converts a value to a JSON string