PHP supports a method known as 'serialize (Object)' that is used to serialize the object. In PHP 7, an additional security feature has been added by introducing filtering 'unserialize (arg1, arg2)' method. This feature seeks to provide better security when unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.
$data = unserialize($serializeObj, ["allowed_classes" => true]);
In above syntax, the first argument is always the serialized object and is mandatory. If we do not pass a serialized object as the first argument then the PHP 7 parser will throw a runtime exception as 'unserialize () expects parameter 1 to be string'. Second argument is optional and if passed, it allows adding additional filter criteria on the serialized class object that is passed as the first argument depending on the following values.
- If the second argument is passed as '["allowed_classes" => true])', unserialize method accepts all classes. It is the default behaviour where the argument 2 value is omitted.
- If the second argument is passed as '["allowed_classes" => false])', unserialize method will converts all objects into
'__PHP_Incomplete_Class'
.
- If the second argument is passed as '["allowed_classes" => ["MyClass", "MyClass2"]])', unserialize method will allow the serialized object (in the first argument) to be among these classes otherwise it will convert all objects into
'__PHP_Incomplete_Class'
.
<?php
class MyClass {
public $datamem1;
}
class MyClass2 {
public $datamem2;
}
// Instantiate the two classes objects
$obj1 = new MyClass();
$obj1->datamem1 = 150;
$obj2 = new MyClass2();
$obj2->datamem2 = 250;
$serializObject1 = serialize($obj1);
$serializObject2 = serialize($obj2);
$data = unserialize($serializObject1, ["allowed_classes" => true]);
$data2 = unserialize($serializObject2, ["allowed_classes" => ["MyClass", "MyClass2"]]);
echo "Result of MyClass data memeber: " . $data->datamem1;
echo "<br />";
echo "Result of MyClass2 data memeber: " . $data2->datamem2;
?>
Output:
Result of MyClass data memeber: 150
Result of MyClass2 data memeber: 250