PHP Filter unserialize()

PHP 7 新特性PHP 7 New Features

PHP 7 adds a feature that allows filtering for unserialize(), which can prevent illegal data from code injection and provides safer deserialization of data.

Examples

Examples

<?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);

// Default behavior is to accept all classes
// The second parameter can be ignored
// 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, only allow MyClass1 and MyClass2 to convert 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 新特性PHP 7 New Features

Other Extensions