Easy Tutorial
❮ Pdostatement Setattribute Func String Sscanf ❯

PHP Filtering unserialize()

PHP 7 New Features

PHP 7 introduces a feature that allows filtering for unserialize(), which prevents illegal data from injecting code, providing safer deserialization of data.

Example

Example

<?php
class MyClass1 { 
   public $obj1prop;   
}
class MyClass2 {
   public $obj2prop;
}

$obj1 = new MyClass1();
$obj1->obj1prop = 1;
$obj2 = new MyClass2();
$obj2->obj2prop = 2;

$serializedObj1 = serialize($obj1);
$serializedObj2 = serialize($obj2);

// The default behavior is to accept all classes
// The second parameter can be omitted
// If allowed_classes is set to true, unserialize will convert all objects to __PHP_Incomplete_Class objects
$data = unserialize($serializedObj1, ["allowed_classes" => true]);

// Convert all objects to __PHP_Incomplete_Class objects, allowing only MyClass1 and MyClass2 to be converted to __PHP_Incomplete_Class
$data2 = unserialize($serializedObj2, ["allowed_classes" => ["MyClass1", "MyClass2"]]);

print($data->obj1prop);
print(PHP_EOL);
print($data2->obj2prop);
?>

The output of the above program is:

1
2

PHP 7 New Features

❮ Pdostatement Setattribute Func String Sscanf ❯