📜  PHP 7-过滤的unserialize()

📅  最后修改于: 2020-10-21 04:57:45             🧑  作者: Mango


PHP 7引入了Filtered unserialize()函数,以便在对不受信任的数据上的对象进行反序列化时提供更好的安全性。它可以防止可能的代码注入,并使开发人员可以将可以反序列化的类列入白名单。

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

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

   // default behaviour that accepts all classes
   // second argument can be ommited.
   // if allowed_classes is passed as false, unserialize converts all objects into __PHP_Incomplete_Class object
   $data = unserialize($serializedObj1 , ["allowed_classes" => true]);

   // converts all objects into __PHP_Incomplete_Class object except those of MyClass1 and MyClass2
   $data2 = unserialize($serializedObj2 , ["allowed_classes" => ["MyClass1", "MyClass2"]]);

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

它产生以下浏览器输出-

1
2